Vectorization with multiple conditionals

2 ビュー (過去 30 日間)
Marcus Rademacher
Marcus Rademacher 2021 年 3 月 19 日
コメント済み: Star Strider 2021 年 3 月 19 日
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 Center および File ExchangeLogical についてさらに検索

タグ

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by