问题描述
我注意到,matlab内置函数可以处理标量或矢量参数.示例:
I've noticed that matlab builtin functions can handle either scalar or vector parameters. Example:
sin(pi/2)
ans =
1
sin([0:pi/5:pi])
ans =
0 0.5878 0.9511 0.9511 0.5878 0.0000
例如,如果我编写自己的函数,则为分段周期性函数:
If I write my own function, for example, a piecewise periodic function:
function v = foo(t)
t = mod( t, 2 ) ;
if ( t < 0.1 )
v = 0 ;
elseif ( t < 0.2 )
v = 10 * t - 1 ;
else
v = 1 ;
end
我可以用单个值来调用它:
I can call this on individual values:
[foo(0.1) foo(0.15) foo(0.2)]
ans =
0 0.5000 1.0000
但是,如果函数的输入是向量,则不会像内置函数那样自动向量化:
however, if the input for the function is a vector, it is not auto-vectorized like the builtin function:
foo([0.1:0.05:0.2])
ans =
1
在函数的定义中是否存在可用于指示向量的语法,如果提供了向量,则应产生向量?还是像sin,cos这样的内建函数会检查其输入的类型,以及输入是否为向量会产生相同的结果?
Is there a syntax that can be used in the definition of the function that indicates that if a vector is provided, a vector should be produced? Or do builtin functions like sin, cos, ... check for the types of their input, and if the input is a vector produce the same result?
推荐答案
您需要稍微更改语法,以便能够处理任何大小的数据.我通常会使用逻辑过滤器对if语句进行矢量化处理,
You need to change your syntax slightly to be able to handle data of any size. I typically use logical filters to vectorise if-statements, as you're trying to do:
function v = foo(t)
v = zeros(size(t));
t = mod( t, 2 ) ;
filt1 = t<0.1;
filt2 = ~filt1 & t<0.2;
filt3 = ~filt1 & ~filt2;
v(filt1) = 0;
v(filt2) = 10*t(filt2)-1;
v(filt3) = 1;
在此代码中,我们有三个逻辑过滤器.第一个选择所有元素,例如t<0.1
.第二个选择所有元素,例如第一个过滤器中没有的t<0.2
.最终的过滤器可以获取其他所有内容.
In this code, we've got three logical filters. The first picks out all elements such that t<0.1
. The second picks out all of the elements such that t<0.2
that weren't in the first filter. The final filter gets everything else.
然后我们使用它来设置向量v
.我们将与第一个过滤器匹配的v
的每个元素都设置为0
.我们在v
中设置所有与第二个过滤器匹配的10*t-1
.我们将与第三个过滤器匹配的v
的每个元素都设置为1
.
We then use this to set the vector v
. We set every element of v
that matches the first filter to 0
. We set everything in v
which matches the second filter to 10*t-1
. We set every element of v
which matches the third filter to 1
.
要更全面地了解矢量化,请查看 MATLAB帮助页面.
For a more comprehensive coverage of vectorisation, check the MATLAB help page on it.
这篇关于如何在MATLAB中向量化分段周期函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!