How do I multiply each column of a matrix by the corresponding element of a vector in MATLAB?

229 views (last 30 days)
How do I multiply each column of a matrix by the corresponding element of a vector in MATLAB?
If I have a large M by N matrix and a vector of length N, how do I easily and quickly multiply each column of the matrix by the corresponding element of the vector?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
There are several ways to multiply each column of a matrix by the corresponding element of the vector. The first is to use the REPMAT function to expand the vector to the same size as the matrix and them perform elementwise multiplication using .* -- however, this will require a large amount of memory.
For example:
To multiply each column of vector b with the row a:
a = [1 2 3]';
b = [1 2; 3 4; 5 6];
x = repmat(a,1,size(b,2));
x.*b % or dot(x,b)
If the matrix involved is a square matrix then the vector can be converted to a diagonal matrix and then multiplied as follows:
Amat = rand(3,3);
b = rand(1,3);
c = Amat*diag(b);
%or
%c = Amat*diag(1./Bvec);
The second method is to use a FOR loop. For long vectors prior to MATLAB 6.5 (R13), this may take a significant amount of time; however, making use of the acceleration technology introduced in MATLAB 6.5 (R13), this time is drastically reduced. If you're using MATLAB 6.5 (R13), copy the following code into a function file for an example that does this:
function B=DivideColumns(N)
% Avoiding creating too large a matrix
if nargin<1 || N >2500
N = 500;
end
tic
A = 1./hilb(N);
c = 1:N;
B = A; % So that we don't overwrite A
T1 = toc;
tic
for i=1:N
B(:,i) = B(:,i)/c(i);
end
T2 = toc;
S1 = sprintf('Constructing the %d by %d ...
A matrix took %f seconds.', N, N, T1);
S2 = sprintf('\nDividing the columns of A ...
by elements of c took %f seconds', T2);
disp([S1 S2])
For large values of N, you can see that generating A will take much more time than performing the division.
Another option is to use a diagonal or sparse diagonal matrix form of your vector. For example, the following code will produce a B that agrees with the B returned by the code above:
function B = TimesDiag(N)
% Avoiding creating too large a matrix
if nargin<1 || N >2500
N = 500;
end
tic
A = 1./hilb(N);
c = 1:N;
T1 = toc;
tic
% Replace this with "B = A*spdiag(c(:),0,N,N);"
% if N is very large:
B = A*diag(c); T2 = toc;
S1 = sprintf('Constructing the %d by %d ...
A matrix took %f seconds.', N, N, T1);
S2 = sprintf('\nDividing the columns of ...
A by elements of c took %f seconds', T2);
disp([S1 S2])

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!