Create matrix by adding elements of two vectors?

2 views (last 30 days)
Hi guys,
I have two vectors:
h =
0 8 16 24 32
g =
0 1 2 3 4 5 6 7
What i want to do is create an MxN matrix such that
M = g(0)+h(0) g(0)+h(1) ..... g(0)+h(end)
g(1)+h(0) g(1)+h(1) ..... g(1)+h(end)
........................................
g(end)+h(0) g(end)+h(1) .....g(end)+h(end)
Can this be performed without having two for loops iterating through each element?

Accepted Answer

the cyclist
the cyclist on 20 Sep 2011
Here's one way:
M = bsxfun(@plus,h,g')
Side note: MATLAB has one-based indexing, not zero-based indexing, so "g(0)" would give you an error, in your example.
  3 Comments
the cyclist
the cyclist on 20 Sep 2011
For future seekers of knowledge, it would be good for you to "accept" this answer if you found it helpful.

Sign in to comment.

More Answers (1)

Sean de Wolski
Sean de Wolski on 20 Sep 2011
In reply to the bsxfun clarification comments:
Think that you are bsxfun. The goal is to apply some function of one of the inputs to every row/column/slice/4th-dimension etc. of the other input. So you have for example a 3x3 and 3x1. How do you do it? You apply the 3x1 to every 3x1 column of the 3x3. If the inputs are 3x3 and 1x3, you apply the 1x3 to every row of the 3x3. If you have a 3x3x3 and a 3x3, then you apply the 3x3 to every third dimensional slice of the Rubik's Cube.
Thus the error when you transpose. If you have a 4x2 and a 1x2 it knows to apply the 1x2 to every row of the 4x2. If you have a 4x2 and a 2x1 (the transpose), if errors out - as it should.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!