3

I have a vector x = [1 2 3] and a 3 by 3 cell array C that consists of N by N matrices. E.g. C{1,1} is an N by N matrix.

I want to multiply x and C and get a cell array D of size 1 by 3:

D{1,1} = x(1)C{1,1) + x(2)C{2,1} + x(3)C{3,1} 
D{1,2} = x(1)C{1,2) + x(2)C{2,2} + x(3)C{3,2} 
D{1,3} = x(1)C{1,3) + x(2)C{2,3} + x(3)C{3,3}
1
  • Honestly, your data is begging to be stored in matrices rather than cell arrays. Commented Nov 21, 2013 at 10:20

2 Answers 2

3

No unrolled loops

For a vector x of length M=3, and an M-by-M cell array C, the idea is to form an M*N-by-M matrix, where column i is composed of all the values in the cells C{i,:}. Then you can use matrix multiplication with x.' to get the values in D, and mat2cell to break up the result into a new cell array.

Ct = C';
Dvals = reshape([Ct{:}],[],M)*x.';
D = mat2cell(reshape(Dvals,N,[]),N,N*ones(M,1))

Test Data:

N = 4; M = 3; x = 1:M;
C = mat2cell(rand(N*M,N*M),N*ones(M,1),N*ones(M,1));

Note: This requires that each sub-matrix is the same size, as in the question.

Sign up to request clarification or add additional context in comments.

Comments

0

With no loops:

D = cell(1, 3);
D{1} = x(1) * C{1,1} + x(2) * C{2,1} + x(3) * C{3,1};
D{2} = x(1) * C{1,2} + x(2) * C{2,2} + x(3) * C{3,2};
D{3} = x(1) * C{1,3} + x(2) * C{2,3} + x(3) * C{3,3};

With one loop:

D = cell(1, 3);
for i=1:3
    D{i} = x(1) * C{1,i} + x(2) * C{2,i} + x(3) * C{3,i};
end

With two loops:

D = cell(1, 3);
for i=1:3
    D{i} = x(1) * C{1,i};
    for j=2:3
        D{i} = D{i} + x(j) * C{j,i};
    end
end

3 Comments

"no loops" doesn't really automate the calculation, does it?
Well, the OP didn't ask for automation, did (s)he? ;)
In that case you could multiply everything by hand and just feed in the results, right? You should know better :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.