使用bsxfun进行Matlab矢量化矩阵减法

时间:2013-05-08 19:52:18

标签: matlab bsxfun

我有一个数组Y=rand(1000,28);我想找到列式差异:

[~ c]=size(Y);

for i=1:c-1
Y(:,i)-Y(:,i+1)
end

我可以使用bsxfun吗?

3 个答案:

答案 0 :(得分:4)

您也可以使用diff

功能执行此操作
dY = -diff(Y, [], 2)

[]2告诉diff沿Y的第二维操作,如您的问题所述。

请注意,这实际上更快,因为diff是内置函数:

>> Y = rand(100, 10000);
>> tic; for n = 1:1000; dY = -diff(Y, [] , 2); end; toc
Elapsed time is 5.453160 seconds.
>> tic; for n = 1:1000; dY = Y(:,1:end-1) - Y(:,2:end); end; toc
Elapsed time is 11.383666 seconds.

编辑:建议使用timeit功能更准确地计算这些时间;结果是:

>> timeit(@()-diff(Y, [] , 2))

ans =

    0.0071

>> timeit(@()Y(:,1:end-1) - Y(:,2:end))

ans =

    0.0119

另外,在这种情况下,将这些放在m文件中似乎没有什么区别。

答案 1 :(得分:3)

请勿使用bsxfun。这样做很简单:

dY = Y(:,1:end-1) - Y(:,2:end)

答案 2 :(得分:0)

Y = rand(1000,28);
[r, c] = size(Y);

Ycol_sub = zeros(r,c-1);

for i=1:c-1
    Ycol_sub(:,i) = Y(:,i)-Y(:,i+1);
end

Ycol_sub2 = bsxfun(@minus, Y(:,1:end-1), Y(:,2:end));

all(all(Ycol_sub == Ycol_sub2))

ans =

       1
相关问题