How do I plot this?? "if, elseif, else"

2 Ansichten (letzte 30 Tage)
Phi Tran
Phi Tran am 9 Feb. 2018
Kommentiert: Phi Tran am 9 Feb. 2018
t=0;
for i=0:50
t=t+1
if (0 <= t && t < 10)
v=(11*(t.^2))-(5*t)
elseif(10 <= t && t <20)
v=1100-(5*t)
elseif(20 <= t && t <30)
v=(50*t) + 2*((t-20)^2)
elseif (t >= 30)
v=1520* exp(-0.2*(t-30))
else
v=0
end
end
%% After I hit run I get a bunch of numbers. I want to plot these values (v vs t).
  1 Kommentar
Adam
Adam am 9 Feb. 2018
You need to store them in an array. This is the most basic part of Matlab and is covered under the 'Getting Started' section when you open the help.
Once you have your arrays then
doc plot
will show you that you can plot them with
plot( t, v )
or, better
plot( hAxes, v, t )
where hAxes is an axes handle you have created from e.g.
figure; hAxes = gca;

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Pawel Jastrzebski
Pawel Jastrzebski am 9 Feb. 2018
Bearbeitet: Pawel Jastrzebski am 9 Feb. 2018
Firstly,
I think that your first loop overwrites the t value instead of creating a vector of t values.
For what you're trying to achieve, consider the following code:
t = 0:50;
% to plot 't' vs 'v' you need the equal amount of
% datapoints in both vectors
v = zeros(1,length(t));
% Use logical vector to meet your condtions
condition1 = (0<=t & t <10);
v(condition1) = 11*(t(condition1).^2) - 5*t(condition1);
condition2 = (10<=t & t<20);
v(condition2) = 1100-5*t(condition2);
% etc.
% plotting
figure
plot(t,v,'ro--');
  2 Kommentare
Guillaume
Guillaume am 9 Feb. 2018
Yes, while it is possible to create v in a loop, it is much simpler to do it the way Pawel is showing, using logical masks.
Phi Tran
Phi Tran am 9 Feb. 2018
thank you

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Line Plots 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