필터 지우기
필터 지우기

Element wise multiplication by a vector

조회 수: 34 (최근 30일)
Moshe
Moshe 2013년 3월 7일
Given a vector V, I can define an element-wise multiplication on another vector W as V.*W. I'd like to be able to likewise multiply the rows or columns of a matrix by a vector V in the same sense. In other words, given a vector with components V(i) and a matrix with components M(i,j), I'd like to output a new matrix W(i,j) whose elements are W(i,j)= V(j) M(i,j).
One way to achieve that, just to demonstrate what I mean, is by using a loop:
for r=1:N
W(r,:)= V.*M(r,:)
end
But, it would be nicer to vectorize that -- I have to use this type of operation many times and the multiple nested loops slow the code down. Attempting something like
W(1:N,:)= V.*M(1:N,:)
does not work, though it really should if you think about both sides as a collection of vectors parametrized by the index 1:N. Any way to accomplish that with a valid Matlab syntax?
This is an example of more general issue, of attempting to vectorize nested loops. A single iterator is usually fairly easy to replace by an index of a matrix, harder to replace nested loops by multiple indices. General advice would be appreciated.

채택된 답변

James Tursa
James Tursa 2013년 3월 7일
편집: James Tursa 2013년 3월 7일
W = bsxfun(@times,V,M)
If V is a row vector you will get V element-wise times each row of M. Similarly if V is a column vector.

추가 답변 (2개)

nanren888
nanren888 2013년 3월 7일
I guess it is the definition of matrix multiply that is getting in your way.
Maybe have a look at diag(V).
It will cost you some space & do a lot of multiplies by zero, but will look neat in code.

Youssef  Khmou
Youssef Khmou 2013년 3월 7일
hi,
Im not sure about your expectations but try Kronecker product :
T=rand(4);
V=1:4;
G=kron(T,V);

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by