Vectorization with multiple conditionals

2 次查看(过去 30 天)
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

采纳的回答

Star Strider
Star Strider 2021-3-19
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 个评论
Marcus Rademacher
Marcus Rademacher 2021-3-19
That works beautifully and is lightning fast. Now that I see your solution it's obvious. Thanks for your help!
Star Strider
Star Strider 2021-3-19
I very much appreciate your compliment!
As always, my pleasure!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by