Writing if function to Plot graph?

29 次查看(过去 30 天)
Phil Whitfield
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
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
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
%your y
else %since that convers the remaning possible x
%y(x)= ...
end
end
then finally plot using plot command
plot(x,y)

jean claude
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)

类别

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