Create matrix by adding elements of two vectors?
3 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
采纳的回答
the cyclist
2011-9-20
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 个评论
the cyclist
2011-9-20
For future seekers of knowledge, it would be good for you to "accept" this answer if you found it helpful.
更多回答(1 个)
Sean de Wolski
2011-9-20
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!