Storing variables from a for loop

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');

Antworten (2)

Rik
Rik am 13 Feb. 2018
Bearbeitet: Rik am 13 Feb. 2018

0 Stimmen

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 Kommentar

Rik
Rik am 24 Feb. 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.

Melden Sie sich an, um zu kommentieren.

Star Strider
Star Strider am 13 Feb. 2018

0 Stimmen

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')

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Tags

Gefragt:

am 13 Feb. 2018

Kommentiert:

Rik
am 24 Feb. 2018

Community Treasure Hunt

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

Start Hunting!

Translated by