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

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.

Leave a Comment