Andrea Ciarmiello
Andrea Ciarmiello

Reputation: 11

Vectors operations in matlab

How subtract each element of row vector of size 1xN from column vector Mx1 without using loop in MatLab?

N = 1:100
M = ones(1000,1)

Upvotes: 1

Views: 68

Answers (1)

Robert Seifert
Robert Seifert

Reputation: 25232

You can use bsxfun as suggested by Daniel

out = bsxfun(@minus, N,M);

but it might be more obvious to use meshgrid or ndgrid to get the matrix you want:

out = meshgrid(N-1,M);

These two functions internally use repmat which is slower than bsxfun, so rather go for the first approach. And bsxfun is always the fastest solution anyway ;)

Upvotes: 2

Related Questions