how to run a loop over an array with matrices and multiply each matrix with an other array?

1 次查看(过去 30 天)
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?

采纳的回答

Guillaume
Guillaume 2017-1-9
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 个评论
summyia qamar
summyia qamar 2017-1-9
actually i want to multiply each array of A with 1st matrix of B and then each array of A with 2nd matrix and so on.. basically A is representing a set of population in genetic algorithm. and I want to check which set gives the best result when treated with B on the given condition
Guillaume
Guillaume 2017-1-9
"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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by