Vectorization with multiple conditionals
2 views (last 30 days)
Show older comments
Marcus Rademacher
on 19 Mar 2021
Commented: Star Strider
on 19 Mar 2021
How can this be vectorized?
t is a monotonically increasing vector of floats. I'm basically dividing the array up into 5 regions and doing different calculations in each region.
out = zeros(length(t), 1);
for i = [1:1:lenght(t)]
if t(i) < t1
out(i) = 0;
continue;
elseif t(i) >= t1 && t(i) <= t2
out(i) = 2 * t(i) + 3;
continue;
elseif t(i) > t2 && t(i) < t3
out(i) = 1;
continue;
elseif t(i) >= t3 && t(i) <= t4
out(i) = -5 * t(i) - 4
continue;
else % t > t4
out(i) = 0;
continue;
end
end
0 Comments
Accepted Answer
Star Strider
on 19 Mar 2021
Try this:
t1 = -5;
t2 = -1;
t3 = 5;
t4 = 8;
fcn = @(t) (t < t1).*0 + ((t >= t1) & (t <= t2)).*(2*t+3) + ((t > t2) & (t < t3)).*1 + ((t >= t3) & (t <= t4)).*(-5*t-4);
t = linspace(-10, 10, 500);
figure
plot(t, fcn(t))
grid
Use your own values for ‘t1’ ... ‘t4’. This is simply an illustration.
.
2 Comments
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!