Using logical AND in an if statement?

811 visualizzazioni (ultimi 30 giorni)
Chris Naron
Chris Naron il 11 Mar 2016
Risposto: Kelly Kearney il 11 Mar 2016
Hi, so I'm working on a problem and have an if statement nested in a for-loop. Basically I can put
if x >= -12
plot(x)
end
and my program will work, but when I add the second statement
if x >= -12 & x < -3
plot(x)
end
Nothing happens at all. I can put the statement
x >= -12 & x < -3
in the console it will give me the values, but I just don't understand why it isn't functioning properly in my if-statement.
Here's the relevant code:
for i = -12 : .5 : 12
x = [-12: .5: 12];
if x >= -12 & x < -3
plot(x)
else
fprintf('error ');
end
end
Also if someone could point me in the right direction on using my for-loop index instead creating variable x with the same values that would be great. Just not too sure on how to make it save each value in a matrix.
Using R2015a
EDIT: It seems that evaluations when x < -3 is causing the issue. I still don't know why. I've tried maxing x > -3, x >=-3, and x <= -3 and I still am not getting any output except for my error message.

Risposte (1)

Kelly Kearney
Kelly Kearney il 11 Mar 2016
When evaluated on a vector, conditional statements return true only if all elements of the vector match the condition. So
x = [-12: .5: 12];
if x >= -12 & x < -3
% do something
end
is the same as
x = [-12: .5: 12];
if all(x >= -12 & x < -3)
% do something
end
And in your case, that statement evaluates as false, so nothing happens.
Logical indexing is the better way to achieve what you want:
x = [-12: .5: 12];
plot(x(x > -12 & x <-3));
or if you want to stick with a for loop and plot each point as a different object (not really recommended, but just for reference), you'll need to index:
hold on;
x = [12:0.5:12];
for ii = 1:length(x)
if x(ii) > -12 && x(ii) < -3
plot(x(ii));
end
end

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by