Possible Duplicate:
How to Add a row vector to a column vector like matrix multiplication
I have a nx1
vector and a 1xn
vector. I want to add them in a special manner like matrix multiplication in an efficient manner (vectorized):
Example:
A=[1 2 3]'
B=[4 5 6]
A \odd_add B =
[1+4 1+5 1+6
2+4 2+5 2+6
3+4 3+5 3+6
]
I have used bsxfun
in MATLAB, but I think it is slow. Please help me...
REPMAT is your friend:
I present a comparison of the different methods mentioned here. I am using the TIMEIT function to get robust estimates (takes care of warming up the code, average timing on multiple runs, ..):
where
The timings:
BSXFUN is a clear winner.
In matlab vectorization, there is no substitute for
Tony's Trick
in terms of speed in comparison torepmat
or any other built in Matlab function for that matter. I am sure that the following code must be fastest for your purpose.The speed differential will be much more apparent (at LEAST an order of magnitude) for larger size of
A
andB
. See this test I conducted some time ago to ascertain the superiority ofTony's Trick
overrepmat
in terms of time consumption.As mentioned by @b3. this would be an appropriate place to use
repmat
. However in general, and especially if you are dealing with very large matrices,bsxfun
normally makes a better substitute. In this case:returns the same result, using about a third the memory in the large-matrix limit.
bsxfun
basically applies the function in the first argument to every combination of items in the second and third arguments, placing the results in a matrix according to the shape of the input vectors.