Star
Star

Reputation: 2299

Apply functions to cell array of matrices in Matlab?

I have 3x3 cells a in Matlab, each cell containing a vector of 9x1

a=cell(3,3);
for i=1:3
    for j=1:3
        a{i,j}=randi(10,[9 1]);
    end
end

I would like to multiply each cell of a by its transpose and then sum across cells but I don't know how to apply these operations to cells.

Upvotes: 0

Views: 75

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112659

I think this does what you want:

M = cellfun(@(v) v*v.', a, 'uni', 0); %'// each vector times its transpose
M = cat(3, M{:}); %// concat along 3rd dim
result = sum(M, 3); %// sum along 3rd dim

Upvotes: 2

Scott
Scott

Reputation: 99

Not sure what you are trying to accomplish here, but if you would like to multiply each cell by its transpose and get the sum of all the elements in that cell you can use something like:

clear all, close all
a=cell(3,3);
b=cell(3,3);
for i=1:3
    for j=1:3
        a{i,j}=randi(10,[9 1]);
        a{i,j} = a{i,j} * a{i,j}.'; % multiply by transpose
        b{i,j} = sum(sum(a{i,j}))
    end
end

Upvotes: 0

Related Questions