Storing variables from a for loop
Afficher commentaires plus anciens
I'm trying to plot a piecewise function using a for loop and if else if statements but the loop only remembers the last value of the variable so only plots one point on the graph. How can I make it plot all the points???
clear
x = -5:0.1:5;
for x = -5:0.1:5
if (x < -3 | x > 3)
y = 3/(x^2-9);
elseif (x == -3 | x == 3)
y = 9;
else
y = 9/(x^2-9);
end
end
scatter(x,y,'r');
axis([-5 5 -15 15])
xlabel('x axis');
ylabel('y axis');
Réponses (2)
You overwrote everything in your loop. You could have used a loop, but then you should have used indices. This problem can be better tackled by using logical indexing (for which you also need to not forget element-wise operation).
x = -5:0.1:5;
y=9*ones(size(x));
condition1=x < -3 | x > 3;
y(condition1)=3./(x(condition1).^2-9);
condition2=x == -3 | x == 3;
y(condition2) = 9;
condition3=~(condition1 | condition2);
y(condition3) = 9./(x(condition3).^2-9);
scatter(x,y,'r');
Using a loop would result in this code:
x = -5:0.1:5;
y=9*ones(size(x));
for i=1:numel(x)
if (x(i) < -3 || x(i) > 3)
y(i) = 3/(x(i)^2-9);
elseif (x(i) == -3 || x(i) == 3)
y(i) = 9;
else
y(i) = 9/(x(i)^2-9);
end
end
scatter(x,y,'r');
1 commentaire
Rik
le 24 Fév 2018
Did this work for you? If not, feel free to post comments here with your remaining questions. If it did solve your problem, please mark it as accepted answer. It will make it easier for other people with the same question to find an answer.
Star Strider
le 13 Fév 2018
Subscript ‘x’ and ‘y’:
The loop becomes:
for k = 1:numel(x)
if (x(k) < -3 | x(k) > 3)
y(k) = 3/(x(k)^2-9);
elseif (x == -3 | x == 3)
y(k) = 9;
else
y(k) = 9/(x(k)^2-9);
end
end
You can use ‘logical indexing’ to do this in a single anonymous function:
yfcn = @(x) ((x < -3) | (x > 3)).*(3./(x.^2-9)) + ((x == -3) | (x == 3)).*9 + ((x>-3) | (x<3)).*((9./(x.^2-9)));
figure(2)
scatter(x, yfcn(x))
xlabel('x axis')
ylabel('y axis')
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!