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