Why my matlab does not enter a loop even when the conditions are true

clear all
Amp=35;
freq=2.3;
for i=1:5
for j=1:4
if Amp== 35 && freq==2.3
robot_speed = 1
end
if Amp== 40 && freq==2.3
robot_speed = 2
end
if Amp== 35 && freq==2.7
robot_speed = 6
end
if Amp== 40 && freq==2.7
robot_speed = 7
end
if Amp== 35 && freq==3.1
robot_speed = 11
end
if Amp== 40 && freq==3.1
robot_speed = 12
end
if Amp== 35 && freq==3.5
robot_speed = 16
end
if Amp== 40 && freq==3.5
robot_speed = 17
end
freq=freq+0.4;
end
freq=2.3;
Amp=Amp+5;
end
Here when the value of Amp becomes equal to 35 and freq becomes equal to 2.7, the robot_speed should be equal to 6 but when I run the code, Matlab is unable to enter the loop even when condition suffices. Loop is traversed only for :
if Amp== 35 && freq==2.3
robot_speed = 1
end
if Amp== 40 && freq==2.3
robot_speed = 2
end
Why is this happening? Someone please help me.

Answers (3)

MATLAB works in binary not in decimal. The only freq value in your code that can be exactly represented in binary is 3.5
Do not compare floating point numbers for exact equality. Consider using ismembertol. Or consider using integers representing tenths and divide them by 10 only when needed in a calculation
Note, rather than an endless list of if statements, you should be using the power of computers who can do look ups very easily:
lookuptable = [35 2.3 1 %Amp, frequency, resulting speed
40 2.3 2
35 2.7 6
40 2.7 7
35 3.1 11
40 3.1 12
35 3.5 16
40 3.5 17];
Amp = 35;
freq = 2.3;
for i = 1:5
for j = 1:4
[matched, matchedrow] = ismembertol([Amp, freq], lookuptable(:, [1 2]), 'ByRows', true);
if matched
robot_speed = lookuptable(matchedrow, 3);
end
freq = freq + 0.4;
end
freq = 2.3;
Amp = Amp + 5;
end
Isn't this simpler (and a lot less typing)?
Thank you for your suggestion. Instead of using my earlier approach, I implemented all the loops as:
if abs(Amp-35) <= 0.001 && abs(freq-2.3) <= 0.001
robot_speed = 1
end

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Asked:

on 6 Mar 2017

Edited:

on 7 Mar 2017

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!