how to run a loop over an array with matrices and multiply each matrix with an other array?
1 view (last 30 days)
Show older comments
I have an array
A = {[10,0,0,10,0,20,15] [0,10,10,15,0,0,20] [0,11,18,0,0,0,17] [0,14,0,17,0,10,0] [18,13,0,0,0,15,0] [0,10,0,0,0,10,15]}
B=<1x10 cell> where each cell is <7x3>matrix
B = <7x3 double> <7x3 double> <7x3 double> <7x3 double> <7x3 double> <7x3 double> <7x3 double> <7x3 double> <7x3 double> <7x3 double>
I want to get the product of each array of A with 1st array of B then apply the whole loop on every array of B and get the result in form of an array of 1x10 cell
I tried this:
[r1,c1]=size(B)
for i=1:c1
for j=1:6
C=A{j}*B{i};
C(C>1)=1;
total=(sum(C))-1;
end
total_movement{j}=movement
end
but this runs a very long loop with zero result..how can I better code it?
0 Comments
Accepted Answer
Guillaume
on 9 Jan 2017
Taking a complete guess at what you're trying to do since the code you've given makes absolutely no sense (total gets overwritten at each step of the loop and in any case is not used outside the loop):
Amat = vertcat(A{:});
total_movement = cell(size(B));
for Bidx = 1:numel(B)
C = A * B{Bidx};
C(C > 1) = 1; %can be simplified to C = C > 1; if all elements of A and B are nonnegative integers
total_movement{Bidx} = sum(C) - 1;
end
There is certainly no point looping over the cell array A when you can just transform into a 2D matrix and multiply that with each B matrix.
2 Comments
Guillaume
on 9 Jan 2017
"multiply each array of A with 1st matrix of B and then each array of A with 2nd matrix and so on":
Amat = vertcat(A(:});
AtimesB = cellfun(@(b) A*b, B, 'UnformOutput', false);
will result in a cell array the same size as B, where each cell is a matrix whose rows are the result of A{j}*B{i}.
Do whatever you want with that.
More Answers (0)
See Also
Categories
Find more on Matrix Indexing 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!