How to create a piecewise function with if and else statements?
2 views (last 30 days)
Show older comments
I'm writing a simple script to model a rocket's velocity (piecewise function) as it launches out to space. The script works well when I input single instances of time. But when I input a range of times, the if-elseif system doesn't seem to work.
t = [-5:30]
vel = vRocket(t)
plot(t,vel)
This is the function vRocket:
function v = vRocket(t)
if 0<=t & t<=8
v = 10.*t.^2 - 5.*t;
elseif 8<=t & t<=16
v = 624 - 5.*t;
elseif 16<=t & t<=26
v = 36.*t + 12 .* (t-16).^2;
elseif t>26
v = 2136 .* exp(-0.1.*(t-26));
elseif t<0
v = 0;
end
The error I get: "Output argument "v" (and maybe others) not assigned during call to "vRocket". Where did I go wrong?
The last part would be to plot the piecewise function, which I haven't figured out as it is not plotting all sections of the function.
0 Comments
Answers (2)
Walter Roberson
on 6 Sep 2016
You are passing a vector to vRocket and you are testing the vector with conditions such as
if 0<=t & t<=8
When you test a vector in MATLAB, the test is only considered true if all of the values are non-zero. If any of the values fail the condition, then the test as a whole fails. But you have tests all the way down, with no case for all of the tests failing, so you never assign anything to v.
You should either be looping over the elements in t, or you should be using logical indexing (the recommended solution)
mask = 0<=t & t<=8;
v(mask) = 10.*t(mask).^2 - 5.*t(mask);
0 Comments
Andrei Bobrov
on 6 Sep 2016
t = -5:30;
t0 = [-inf 0 8 16 26 inf];
[~,ii] = histc(t(:),t0);
f = {@(t)zeros(size(t));
@(t)10.*t.^2 - 5.*t;
@(t)624 - 5.*t;
@(t)36.*t + 12 .* (t-16).^2;
@(t)2136 .* exp(-0.1.*(t-26))};
v = zeros(size(t));
a = unique(ii);
for jj = 1:numel(a)
l = a(jj)==ii;
v(l) = f{a(jj)}(t(l));
end
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!