Multiply each element of a vector with a matrix
Mostrar comentarios más antiguos
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?
Respuesta aceptada
Más respuestas (3)
James Tursa
el 8 de Mzo. de 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
el 8 de Mzo. de 2012
Hi,
try kron and reshape:
B = [1 2; 3 4]
A = 1:5
reshape(kron(A,B),[size(B),numel(A)])
6 comentarios
Lars Kluken
el 8 de Mzo. de 2012
Friedrich
el 8 de Mzo. de 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
el 8 de Mzo. de 2012
You can look into the code of KRON. As far as I remember, this is a FOR loop also.
Friedrich
el 8 de Mzo. de 2012
No there isnt. Its meshrgrid and smart indexing
Jan
el 8 de Mzo. de 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
el 8 de Mzo. de 2012
Looking in meshgrid in 2012a it is just a series of reshapes and ones() used for indexing.
Jan
el 8 de Mzo. de 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 comentario
Lars Kluken
el 8 de Mzo. de 2012
Categorías
Más información sobre Programming en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!