# Writing if function to Plot graph?

조회 수: 154(최근 30일)
Phil Whitfield 2017년 10월 10일
답변: jean claude 2017년 10월 10일
So I have to write a script that creates a vector with x =1 :35 and then evaluates tusing an if statement
y(x)={2 if x<6 ,(x-4) if 6=<x<20,(36-x) if 20=<x+,35}
which then plots y against x and calculates the min and max values of the curve.
What I have written is this:
x = 1:35 ;
for y=(x)
if x < 6
x=2;
elseif x>=6
then x = (x-4);
elseif x>=20
then x = (36-x)
end
end
plot(y,x)
however it doesn't really plot anything.
Can anyone show me where I have gone wrong at all?
Thanks
##### 댓글 수: 1표시숨기기 없음
Rik 2017년 10월 10일
I would recommend a crash course. There are several free online tutorials you can do.
The loop index in the for-loop is not used, therefore y is 35 by definition and x=2. If you change it around, you would get errors, because Matlab doesn't use then as a key word.
Morale of the story: don't do this with a loop. Do this with logical indexing.

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

### 답변(2개)

KL 2017년 10월 10일
You have tried something but you have got very few things wrong. Firstly when they say
y(x)={2 if x<6 ,
(x-4) if 6=<x<20,
(36-x) if 20=<x+,35}
it means, y takes different values based on x and not x should be reassigned.
You have created x rightly in the beginning with the following line
x = 1:35;
Next you just need to calculate different y inside a for loop. To do that, just have a look at the documentation of for loop
Anyway, simple idea is,
for x
if x<6
%y(x) = ..
elseif x>=6 && x<20 %here you see, two conditions in the same line
else %since that convers the remaning possible x
%y(x)= ...
end
end
then finally plot using plot command
plot(x,y)
##### 댓글 수: 0표시숨기기 이전 댓글 수: -1

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

jean claude 2017년 10월 10일
you can use this code
y=zeros(35,1);
for x = 1:35
if x < 6
y(x)=2;
elseif 6<= x && x<20
y(x)= x-4;
elseif x>=20
y(x)=36-x;
end
end
x=1:35;
plot(x,y)

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

### Community Treasure Hunt

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

Start Hunting!

Translated by