Diagonal of a multiplication between matrix without doing the actual multiplication or using a loop
Show older comments
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
Image Analyst
on 23 Jul 2016
"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?
Answers (2)
Azzi Abdelmalek
on 23 Jul 2016
Edited: Azzi Abdelmalek
on 23 Jul 2016
%------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)]'
1 Comment
Azzi Abdelmalek
on 23 Jul 2016
Edited: Azzi Abdelmalek
on 23 Jul 2016
A=sym(randi(10,3))
B=sym(randi(10,3))
out=sum(A'.*B)
jerome
on 23 Jul 2016
0 votes
Categories
Find more on Calculus in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!