필터 지우기
필터 지우기

How can I plot a for loop?

조회 수: 1 (최근 30일)
Mike Holbach
Mike Holbach 2015년 3월 3일
답변: Star Strider 2015년 3월 3일
Can someone tell me what's wrong with this code? It is only plotting at x=6 because the loop obviously ends there.
e=2.718;
for x=-2:1:6
if x<-1
y=e.^(x+1)
elseif x>=-1 && x<5
y=2+cos(pi.*x)
elseif x>=5
y=10.*(x-5)+1
else
fprintf('answer not given')
end
end
x=-2:6;
plot(x,y)
Thanks you

채택된 답변

Star Strider
Star Strider 2015년 3월 3일
You’re not subscripting either ‘x’ or ‘y’. That’s important because ‘x’ is negative and zero, so it can’t be used as indices. Also, the lengths of both vectors have to be the same.
A few tweaks and your code works:
e=2.718;
x=-2:1:6;
for k1 = 1:length(x)
if x(k1)<-1
y(k1)=e.^(x(k1)+1);
elseif x(k1)>=-1 && x(k1)<5
y(k1)=2+cos(pi.*x(k1));
elseif x>=5
y(k1)=10.*(x(k1)-5)+1;
else
fprintf('\nanswer not given\n')
y(k1) = NaN;
end
end
x=-2:6;
plot(x,y)

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by