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
0 个评论
采纳的回答
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!