Matlab中循环和向量化的比较 [英] comparison of loop and vectorization in matlab

查看:105
本文介绍了Matlab中循环和向量化的比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑以下脉冲函数代码

let us consider following code for impulse function

function y=impulse_function(n);
y=0;
if n==0
    y=1;
end
end

此代码

>> n=-2:2;
>> i=1:length(n);
>> f(i)=impulse_function(n(i));
>> 

返回结果

 f

f =

     0     0     0     0     0

这段代码

>> n=-2:2;
>> for i=1:length(n);
f(i)=impulse_function(n(i));
end
>> f

f =

     0     0     1     0     0

在两种情况下我都是1 2 3 4 5,有什么不同?

in both case i is 1 2 3 4 5,what is different?

推荐答案

您的函数未定义为处理矢量输入.

Your function is not defined to handle vector input.

按如下所示修改您的实现函数:

Modify your impluse function as follows:

function y=impulse_function(n)
    [a b]=size(n);
    y=zeros(a,b);
    y(n==0)=1;
end

在您定义impulse_function时,会将整个数组与零进行比较,并且返回值仅是一个数字而不是向量.

In your definition of impulse_function, whole array is compared to zero and return value is only a single number instead of a vector.

这篇关于Matlab中循环和向量化的比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆