Filter löschen
Filter löschen

Writing if function to Plot graph?

29 Ansichten (letzte 30 Tage)
Phil Whitfield
Phil Whitfield am 10 Okt. 2017
Beantwortet: jean claude am 10 Okt. 2017
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 Kommentar
Rik
Rik am 10 Okt. 2017
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.

Melden Sie sich an, um zu kommentieren.

Antworten (2)

KL
KL am 10 Okt. 2017
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 am 10 Okt. 2017
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)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by