How to sum a multiple pairing array matrix from element multiplication of array of cell

1 view (last 30 days)
Hi,
I have my cell, A=cell(1,16) and each of the array matrix in the cell consists of zeros(128). From the cell I did the element multiplication to get the pairing matrix of E(1,1), E(1,2)..till...E(16,16). Each pairing matrix also will have zeros(128). From that pairing matrix how can I sum up all the pairing matrixes so that I can only have one matrix, B that contains of zeros(128)?
This is the code that I have, please advice. The error appears at the code of getting the total.
for i=1:16;
m1=A{1,i};
for j=1:16
m2=A{1,j};
c=m1.*m2; % Do the element multiplication to get E(i,j)
E{i,j}=c;
end
end
%-------- Total ---------------------
B = zeros(128);
for n=1:16;
for m=1:16;
B = B + sum(E{n,:});
end
end

Answers (2)

Guillaume
Guillaume on 20 Nov 2015
If I've understood correctly, you've overcomplicated the summation and it should simply be:
B = B + E{n ,m};
within the loop.
However, you could avoid all your loops by using N-D matrices instead of cell arrays:
A = arrayfun(@(x) ones(128)*x, 1:16, 'UniformOutput', false); %demo A
AA = cat(3, A{:}); %concatenate all your A into a 3d matrix
EE = bsxfun(@times, AA, permute(AA, [1 2 4 3]); %EE is a 4d matrix
%EE(:, :, n, m) is the same as your E{n, m}
BB = sum(sum(EE, 3), 4); BB is the same as your B

yasmin
yasmin on 20 Nov 2015
Hi,
Thank you for replying my question. I have change it as you suggested and it works well.

Community Treasure Hunt

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

Start Hunting!