Multiply each element of a vector with a matrix
Ältere Kommentare anzeigen
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?
Akzeptierte Antwort
Weitere Antworten (3)
James Tursa
am 8 Mär. 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
am 8 Mär. 2012
Hi,
try kron and reshape:
B = [1 2; 3 4]
A = 1:5
reshape(kron(A,B),[size(B),numel(A)])
6 Kommentare
Lars Kluken
am 8 Mär. 2012
Friedrich
am 8 Mär. 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
am 8 Mär. 2012
You can look into the code of KRON. As far as I remember, this is a FOR loop also.
Friedrich
am 8 Mär. 2012
No there isnt. Its meshrgrid and smart indexing
Jan
am 8 Mär. 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
am 8 Mär. 2012
Looking in meshgrid in 2012a it is just a series of reshapes and ones() used for indexing.
Jan
am 8 Mär. 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 Kommentar
Lars Kluken
am 8 Mär. 2012
Kategorien
Mehr zu Logical finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!