Multiply each element of a vector with a matrix
Show older comments
I want to multiply each element of a vector with a matrix such that I end up with a 3D matrix (or higher dimentions).
For example if A is a vector and B is a matrix I would write:
for indx=1:length(A)
result(:,:,indx)=A(indx).*B
end
Is for-loops the way to go here or are there any better solutions?
Accepted Answer
More Answers (3)
James Tursa
on 8 Mar 2012
Yet another method for completeness using an outer product formulation. May not be any faster than bsxfun et al:
result = reshape(B(:)*A(:).',[size(B) numel(A)]);
(This tip actually comes from Bruno via another thread)
Friedrich
on 8 Mar 2012
Hi,
try kron and reshape:
B = [1 2; 3 4]
A = 1:5
reshape(kron(A,B),[size(B),numel(A)])
6 Comments
Lars Kluken
on 8 Mar 2012
Friedrich
on 8 Mar 2012
Every other way I can think of is more complex and not very fast. So its seems that a for loop is the best way here.
Jan
on 8 Mar 2012
You can look into the code of KRON. As far as I remember, this is a FOR loop also.
Friedrich
on 8 Mar 2012
No there isnt. Its meshrgrid and smart indexing
Jan
on 8 Mar 2012
I feel so blind without a Matlab installation. Is MESHGRID free of FOR loops now? I've read all the basic function in Matlab 4, 5.3, 6.5, 2008b, 2009a. Now I'm starting to get confused when I read them in 2011b again. It would be so nice to have a list of changes for each function...
Sean de Wolski
on 8 Mar 2012
Looking in meshgrid in 2012a it is just a series of reshapes and ones() used for indexing.
Jan
on 8 Mar 2012
Did you pre-allocate the output?
result = zeros([size(B), length(A)]);
for indx = 1:length(A)
result(:, :, indx) = A(indx) .* B;
end
Or:
for indx = length(A):-1:1 % Backwards for pre-allocation
result(:, :, indx) = A(indx) .* B;
end
1 Comment
Lars Kluken
on 8 Mar 2012
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!