How do I plot this?? "if, elseif, else"
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Phi Tran
il 9 Feb 2018
Commentato: Phi Tran
il 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 Commento
Adam
il 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;
Risposta accettata
Pawel Jastrzebski
il 9 Feb 2018
Modificato: Pawel Jastrzebski
il 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 Commenti
Guillaume
il 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.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Graphics Performance in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!