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');
답변 (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
Rik
2018년 2월 24일
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
2018년 2월 13일
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')
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!