Ashutosh Singla
Ashutosh Singla

Reputation: 739

How to add rows of 3D cell

I have 3-D (60x72x29) cell arrays with numbers inside, and I want to add the rows across the 3rd dimension so that the resulting cell size should be (60x72). Is there any elegant way to do this?

Upvotes: 0

Views: 26

Answers (1)

Suever
Suever

Reputation: 65430

The elegant way is to not use a cell array to hold multi-dimensional numeric data where each element only contains a scalar. MATLAB is optimized for dealing with multi-dimensional numeric arrays so you should convert your data to that format using cell2mat.

Once it is a multi-dimensional numeric array, you can use sum combined with the second input which specifies the dimension along which to perform the operation.

data = cell2mat(old_data);
S = sum(data, 3);

If you really need a cell array back, you can use num2cell on the result to turn it back into a cell array

C = num2cell(S);

Update

It looks like your initial data is a cell array of strings. If that's the case, you can instead use str2double convert the cell array of strings to a numeric array

data = str2double(old_data);
S = sum(data, 3);

Upvotes: 2

Related Questions