How to subtract a vector from each row of a matrix? [duplicate]

元气小坏坏 提交于 2019-11-27 04:58:38

Here is my contribution:

c = b - ones(size(b))*diag(a)

Now speed testing it:

tic
for i = 1:10000
    c = zeros(size(b));
    b = rand(7,3);
    c = b - ones(size(b))*diag(a);
end
toc

The result:

Elapsed time is 0.099979 seconds.

Not quite as fast, but it is clean.

There are only three obvious answers, and you gave two of them in your question.

The third is by row,

c(1,:) = b(1,:) - a; %...

but I'd expect that to be slower than your by-column processing for large matrixes since it accesses elements out of memory order.

If you turn your by-column processing into a for loop in a *.m file or subfunction, is it still faster than the repmat version?

One other thing you might test for speed: Try preallocating c.

c = zeros(size(b));
c(:,1) = b(:,1) - a(1); %...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!