# Potting graphs with if else and for

조회 수: 1 (최근 30일)
Gayathri Thilakrathne 2020년 11월 5일
편집: Walter Roberson 2021년 1월 7일
Here i wanted to plot a graph wit these conditions. but it does not plot a graph. figure remains empty without a graph. how can i fix this
t = -4:0.1:4;
for k1 =1:length(t)
if (t(k1)>-4) && (t(k1)<-2)
x(k1) = (t(k1).^2) - (2.*t(k1))+3;
elseif (t(k1)>-2) && (t(k1)<2)
x(k1) = 4*cos(t(k1)*(2*pi*t(k1) - pi./8)) + 3*sin(2*pi*t(k1));
elseif (t(k1)>2) && (t(k1)<4)
x(k1) = sin(t(k1))./t(k1);
end
end
plot (t,x)

댓글을 달려면 로그인하십시오.

### 채택된 답변

Sindar 2020년 11월 5일
If it throws an error, please include that information.
If that error is what I'm seeing:
Error using plot. Vectors must be the same length.
then the issue is that you're conditions don't include an x-value when t=4 (or -2,2, but these will be filled in with zeros). You can use <=, >=, or you don't want those points plotted, insert NaNs:
t = -4:0.1:4;
for k1 =1:length(t)
if (t(k1)>-4) && (t(k1)<-2)
x(k1) = (t(k1).^2) - (2.*t(k1))+3;
elseif (t(k1)>-2) && (t(k1)<2)
x(k1) = 4*cos(t(k1)*(2*pi*t(k1) - pi./8)) + 3*sin(2*pi*t(k1));
elseif (t(k1)>2) && (t(k1)<4)
x(k1) = sin(t(k1))./t(k1);
else
x(k1) = nan;
end
end
plot(t,x)
##### 댓글 수: 1이전 댓글 -1개 표시이전 댓글 -1개 숨기기
Gayathri Thilakrathne 2020년 11월 5일
Thank you very much!

댓글을 달려면 로그인하십시오.

### 카테고리

Help CenterFile Exchange에서 2-D and 3-D Plots에 대해 자세히 알아보기

### Community Treasure Hunt

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

Start Hunting!

Translated by