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

1 回表示 (過去 30 日間)
Phi Tran
Phi Tran 2018 年 2 月 9 日
コメント済み: Phi Tran 2018 年 2 月 9 日
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 件のコメント
Adam
Adam 2018 年 2 月 9 日
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;

サインインしてコメントする。

採用された回答

Pawel Jastrzebski
Pawel Jastrzebski 2018 年 2 月 9 日
編集済み: Pawel Jastrzebski 2018 年 2 月 9 日
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 件のコメント
Guillaume
Guillaume 2018 年 2 月 9 日
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 2018 年 2 月 9 日
thank you

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeGraphics Performance についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by