1

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) 
2
  • 1
    Take a look at bsxfun Commented Apr 11, 2015 at 12:53
  • What you ask is unclear ... can you precise the expected output ? Commented Apr 11, 2015 at 12:53

1 Answer 1

2

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 ;)

Sign up to request clarification or add additional context in comments.

3 Comments

bsxfun for the win!
If the number of columns in vector and in Matrix are different bsxfun works all the way?... For e.g In my setting i have N=[12 33 2 45 8 1 67 5 58] M is a Matrix of 100 rows and 4 columns I need to subtract each element of N from each Matrix value can i do this with bsxfun? Thanks
@AndreaCiarmiello bsxfun works for a = 1xN and b = Mx1 or a = MxN and b = MxN. What you want won't work, as it is unclear how the result should look like. You should post a new question with a minimal example and the desired output for a given input. There will be an efficient solution as well, but its a different question then. Please consider also accepting this answer, if it helped you for now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.