MATLAB:无法使用输入向量正确评估函数

时间:2014-07-15 02:56:51

标签: matlab vector

我正在尝试将向量传递给函数,并通过分段函数计算向量。当我运行下面的代码时,我只返回一个数字而不是一个向量。有什么想法吗?

谢谢!

t[-5:1:50]
velocity(t)

function [v] = velocity( t )

%This function takes vector 't' and evaluates a velocity over a given
%piecewise function

if t>=0 & t<=8
v=10*t^2-5*t;

elseif t>=8 & t<=16
v=624-5*t;

elseif t>=16 & t<=26
v= 36*t+12*(t-16)^2;

elseif t>26
v=2136*exp(-0.1*(t-26));
else t<0

end

1 个答案:

答案 0 :(得分:0)

当您将矢量提升到正方形时,您正在使用自身执行标量积。

t^2替换为t.^2以获取元素操作符。

(t-16).^2执行相同操作。

所有其他操作符应自动落入元素明智的情况,但您可以在它们之前添加点以确保。

此外,您编写的条件适用于t作为标量值。您可以通过执行以下操作获得研究效果:

而不是

if cond1:
    v = something
elif cond2:
    v = something_else

indices1 = (cond1)  % where cond1 is t < 10 for example
indices2 = (cond2)  % and cond2 is t >= 10
v[indices1] = something
v[indices2] = something_else

我希望你明白这一点。

相关问题