%
% Matrix multiplication D*A or A*D, where D is a diagonal matrix (nonzeros
% stored in a vector d)
%
%
clear all
n=1000;
A=rand(n);
C1=zeros(n);
C2=zeros(n);
C3=zeros(n);
d=rand(n,1);
D=diag(d);
%
% product C = D*A   (left multiplication)
%
tic
for i=1:n
    C1(i,:)=d(i)*A(i,:);    % access A by rows
end
toc

tic
for j=1:n
    C2(:,j)=d.*A(:,j);     % (better) access A by columns
end
toc

%
% product C = A*D   (right multiplication)
%
tic
for j=1:n
    C3(:,j)=d(j)*A(:,j);    % access by columns
end
toc

%
% check results
%
norm(C1-D*A),norm(C2-D*A),norm(C3-A*D)

