I have a cell array size 1x200x201, in each cell is 2x2 matrix. I need to multiply the matrices in a way that I would get resulting matrix: 2x2x201. Which means: Cell_M{1,1,1}* Cell_M{1,2,1}*Cell_M{1,3,1}*...
and so on up to 200, and the same up to 201 ( Cell_M{1,1,2}* Cell_M{1,2,2}*Cell_M{1,3,2}*...
). Cell arrays is just a way for handling the data. Is any effective way to do this multiplications?
Asked
Active
Viewed 342 times
1

Mohsen Nosratinia
- 9,844
- 1
- 27
- 52

Essential_M
- 13
- 2
-
don't you mean you want a resulting matrix with a size of size 2x200x201? – Lucius II. Aug 08 '13 at 09:36
-
1Can you make a mock up using for loops for a much smaller data set, say 1x2x3 ? – Dan Aug 08 '13 at 09:38
-
200 - are different layers from measured sample, and 201 are different angles, in the end I need to have the values for all the angles. – Essential_M Aug 08 '13 at 09:52
-
The resulting matrix should be 2x2x201 for every angle: multiply all 200 matrices (in layers) together. The number of angles and layers can change in general code. That's quite problematic because I need to make all that many matrices multiplication – Essential_M Aug 08 '13 at 09:55
1 Answers
1
Floating-point matrix multiplication is not associative in general, so A*B*C*D
is ambiguous. In this code I assume you are looking for ((A*B)*C)*D
d=size(Cell_M);
P = cell(d(1), 1, d(3));
P(:)={eye(2)};
for k=1:d(2),
P = cellfun(@mtimes, P(:,1,:), Cell_M(:,k,:), 'UniformOutput', false);
end
P = squeeze(P);
Now P
will be a cell array of 201 elements where each element is a 2-by-2 matrix.

Mohsen Nosratinia
- 9,844
- 1
- 27
- 52
-
wow, thanks- it looks like this is what I was looking for. Very smart. Yes, I know that mathematically this multiplication is not associative, but, yes in this case I assume ((A*B)*C)... Thanks again to Mohsen. – Essential_M Aug 08 '13 at 10:25
-
1Matrix multiplication is associative! http://en.wikipedia.org/wiki/Matrix_multiplication#Properties_of_the_matrix_product_.28any_number.29 – knedlsepp Jan 01 '15 at 14:48
-
1@knedlsepp I wasn't specific enough. It is associative with infinite precision but not with finite-precision floating point representation. Simple addition and multiplication are not associative either: `(1 + 1e30) - 1e30 == 0` but `1 + (1e30 - 1e30) == 1`, also look at this http://stackoverflow.com/questions/6430448/why-doesnt-gcc-optimize-aaaaaa-to-aaaaaa Thanks for bringing it up, I edited the answer. – Mohsen Nosratinia Jan 02 '15 at 16:41
-
Thanks for editing the answer! I guess for beginners, going into too much detail on numerics might be overkill. I especially got nervous when I read @Essential_M's answer: *I know that mathematically this multiplication is not associative*, which makes me think he might have misunderstood. Just acting on the maxim: "Don't expect equality for floating points" might be good enough as a general rule, because well, mathematically it should be associative. – knedlsepp Jan 02 '15 at 21:14