Vectorization with multiple conditionals
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Marcus Rademacher
am 19 Mär. 2021
Kommentiert: Star Strider
am 19 Mär. 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 Kommentare
Akzeptierte Antwort
Star Strider
am 19 Mär. 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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Logical 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!