Diagonal of a multiplication between matrix without doing the actual multiplication or using a loop

Hi,
I'm interesting in multiplying the first row of a matrix, the second row with second column and so on. Therefore I am interested in finding the diagonal of the multiplication between 2 matrix.
at first I used the code :
fctvg = matchsetg*fctv0g
goodfctg=diag(fctvg).'
But it do all the multiplications and I'm only interest in the diagonal, this process was taking many hours so I decide to use a for loop:
for hh=1:ntype;
goodfctg(hh,1)=matchsetg(hh,:)*fctv0g(:,hh);
end;
This drastically reduce the time, but I'm trying to vectorize this equation to improve further, nevertheless I fail to find the correct code. For example:
ii= 1:1:ntype;
goodfctg(ii,1)=matchsetg(ii,:)*fctv0g(:,ii);
Does not work. It must be a simple mistake, thanks for the help.

1 Comment

"I'm interesting in multiplying the first row of a matrix," by what????? It has to be multiplied by something.
Then, if you want to multiply "the second row with second column" then, since you seem to have two matrices, the number of columns in the first matrix must equal the number of rows in the second matrix since to do an element by element multiplication of "the second row with second column" the second row must have the same number of elements as the second column. If matrix 1 is r1-by-c1 and matrix 2 is r2-by-c2, then c1 must equal r2. Is that the case? Assuming so, then the output of this multiplication will be a c1-by-1 row or column vector. Please provide small example arrays.
Since the output is a vector, and you're multiplying the row by the column, I don't understand what you say when you talk about "finding the diagonal of the multiplication between 2 matrix" Are you planning on extracting just one value out of the column or row matrix and throwing the rest away?

Sign in to comment.

Answers (2)

%------Example-------------
A=randi(10,3)
B=randi(10,3)
%-----------The code----------
C=reshape(A,[],1,3)
D=reshape(B,[],1,3)
out1=sum(bsxfun(@times,A,B'),2)
%---------Check the result-------
out2=[A(1,:)*B(:,1) A(2,:)*B(:,2) A(3,:)*B(:,3)]'
Thanks I try it before the problem is that element are sym so bsxfun does not work.

Asked:

on 23 Jul 2016

Edited:

on 23 Jul 2016

Community Treasure Hunt

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

Start Hunting!