Loops and Complicated Matrix Multiplication
1 view (last 30 days)
Show older comments
Hello,
This may be simple to figure out but for some reason I can't seem to get the results I want.
I'm trying to multiply two matrices together using a loop, in which the matrix dimensions do not agree. I know this impossible to do using the standard matrix arithmetic. What I would like to do is multiply each column from matrix (Txcouple 41x40x40) against a page in the other matrix (dpTxcouple1 41x17x1600). There should be 1600 pages in the resulting answer but I am unsure how to do this. Here is what I have so far. I can manage to populate the first page with the correct result, but the other pages are filled with zeros.
for k=1:40;
for m=1:17
for g=1:40;
for i=(f-1) * 40 + g;
Tx1Final(:,m,i)=Txcouple(:,k,g).*dpTxcouple1(:,m,i);
end
end
end
end
Any help would be greatly appreciated.
Thanks!
Josh
3 Comments
Accepted Answer
Matt Fig
on 5 Sep 2012
Edited: Matt Fig
on 5 Sep 2012
Often times it is easier to figure out such a problem by looking at a simpler version where we can actually keep track manually. Here I compare three methods that yield the same result. You have not answered the question I posted above, but from your description I tried this. Look and see if it works by comparing T,H, and C. If these do what you want, then adapt for your use.
T = randi(10,3,2,2); % Data we can inspect without getting lost!
H = randi(10,3,5,4); % Use these to develop a general approach.
% Method 1, the obvious approach.
C = zeros(size(H));
for ii = 1:size(H,3)
for jj = 1:size(H,2)
C(:,jj,ii) = T(:,ii).*H(:,jj,ii);
end
end
% Method 2. Vectorize inner FOR loop. Faster.
C2 = zeros(size(H));
for ii = 1:size(H,3)
C2(:,:,ii) = bsxfun(@times,H(:,:,ii),T(:,ii));
end
% Method 3, definitely more advanced (and faster still!)
[r,c] = size(T);
C3 = bsxfun(@times,H,reshape(T,r,1,c));
isequal(C,C2,C3) % Yes...
0 Comments
More Answers (1)
Azzi Abdelmalek
on 5 Sep 2012
Edited: Azzi Abdelmalek
on 5 Sep 2012
[n,m,l]=size(A);[n1,m1,l1]=size(B);v=[];
for i1=1:l
for k=1:m
v=[v bsxfun(@times, A(:,i1,k),B)];
end
end
0 Comments
See Also
Categories
Find more on Graphics Object Programming 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!