Tetra
Tetra

Reputation: 747

Cellfun : How to sum each row in a cell array of matrices? Matlab

Say I have 3x3 cells, each cell containing a matrix of 9x9, how would I go about using cellfun to sum each row of the entire cell array?

I keep obtaining the error ''bad cell reference'' when I try to use the : in the curly brackets.

I'd rather not convert it to a matrix then back to cells again.

Many thanks for your wisdom guys!

Upvotes: 0

Views: 10829

Answers (3)

gevang
gevang

Reputation: 5014

If you mean sum each row in each cell entry maybe you can do something like this:

% random input
A = cell(3,3);
for i=1:9
    A{i} = randi(9,3,3);
end;

B = cellfun(@(x) sum(x, 2), A, 'UniformOutput', false);

Update: To sum all rows across the cell array, as if it was a matrix, without converting to a matrix modify the above as:

B = num2cell(zeros(3, 1)); % initialize
for i=1:3
    B = cellfun(@plus, B, A(:,i), 'UniformOutput', false); % add column-wise
end
B = cellfun(@(x) sum(x, 2), B, 'UniformOutput', false); % add within each remaning cell

This will give a 3x1 cell of 3x1 arrays with the sums across rows.

Upvotes: 2

Autonomous
Autonomous

Reputation: 9075

Here is the solution for summing row of each matrix with a cell , if you read the documentation of cellfun carefully, I think you should be able to get it.

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

row_sum_cell=cellfun(@(a) sum(a,2),a,'UniformOutput',false);

The following solution sums the entire row across the cell array:

clc;
clear all;
a=cell(3,3);
for i=1:3
    for j=1:3
        a{i,j}=randi(10,[9 9]);   %generating the cell array
    end
end

[r,c]=size(a);          %getting the size of the array to concatenate it at runtime
horzCat_A=cell(r,1);

for i=1:r
    for j=1:c
        horzCat_A{i,1}=[horzCat_A{i,1} a{i,j}];    %concatenating
    end
end

%after getting a concatenated matrix, apply a cellfun same as in previous example.
cell_row_sum=cellfun(@(horzCat_A) sum(horzCat_A,2),horzCat_A,'UniformOutput',false);

Upvotes: 0

Gunther Struyf
Gunther Struyf

Reputation: 11168

Another option is to use cell2mat and num2cell:

a=num2cell(randi(10,3)); % random input generation

result = num2cell(sum(cell2mat(a),2));

Next question is then: Why are you working with a cell matrix of scalars? Can't you just work with an ordinary matrix (which you can obtain using cell2mat)?

Upvotes: 0

Related Questions