- work with integers, or
- use tolerances when comparing (i.e. do not use exact equality), avoid FIX, etc.
Why loop is not being excluded with the given condition?
1 view (last 30 days)
Show older comments
Muhammad Hassaan Bin Tariq
on 18 Oct 2022
Commented: Muhammad Hassaan Bin Tariq
on 18 Oct 2022
I am using the continue function to exclude the nodes of a sine function in matlab. When I start from 0, it is excluding all the nodes. However, when I start from 0.1 (for some reasons), it does not exclude the nodes i.e. 1.5, 2.5, 3, 3.5. Can you tell me what can be the reason and how to deal with it?
F_b = 16000; % N
A_b = 125.66; % mm^2
for cycles = 0:0.1:10
if cycles/0.5 == fix(cycles/0.5)
continue
end
disp(cycles)
end
The other is
F_b = 16000; % N
A_b = 125.66; % mm^2
for cycles = 0.1:0.1:10
if cycles/0.5 == fix(cycles/0.5)
continue
end
disp(cycles)
end
Thanks for the help in advance.
Regards,
Muhammad Hassaan Bin Tariq
2 Comments
Stephen23
on 18 Oct 2022
"Can you tell me what can be the reason..."
Because 0.1 cannot be exactly stored in a binary floating point number (in exactly the same way that you cannot write 1/3 exactly on a piece of paper using a decimal fraction). The floating point error accumulates differently in the COLON operator, depending on the provided values. Lets compare:
cycles0 = 0:0.1:10;
cycles1 = 0.1:0.1:10;
fprintf('%.40f\n', cycles0(16)/0.5, fix(cycles0(16)/0.5), cycles1(15)/0.5, fix(cycles1(15)/0.5))
"...and how to deal with it?"
Either:
Your current approach is numerically fragile and should be avoided.
Accepted Answer
Tobias Panitz
on 18 Oct 2022
Hey,
have you tried using the modulus function?
if mod(cycles,0.5) == 0
continue;
end
0 Comments
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!