John Alberto
John Alberto

Reputation: 437

Accessing data of a cell in MATLAB?

I was hoping I could get some help using the cellfun function in MATLAB.

Let's say I have cell that contains 5 10x2 matrices, i.e.

C = {[10x2], [10x2]...,[10x2]} 

However, I want a new cell that takes the first 5 rows across both columns in each array, i.e. I want

D = {[5x2], [5x2]...,[5x2]}

Is there a way to do this in Matlab using cellfun? I tried doing

D = cellfun(@(x) x(1:5),C,'UniformOutput',false)

But then this returned a cell that only contained the first 5 rows of only the first column in each array (and was also transposed) i.e., I got

D = {[1x5], [1x5]...,[1x5]}

Hopefully I explained this well.

Can anyone help? I think there's a simple way to do it but I'm new to cellfun. It seems useful though. Maybe there's an even easier way I'm not seeing?

Upvotes: 0

Views: 84

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112659

Here's another approach, exploiting the fact that all matrices in the cell array have the same size:

  1. Concatenate all those matrices along the third dimension;
  2. Keep only the desired rows;
  3. Convert back from 3D-array to cell array.

Code:

N = 5; %// number of rows to keep
D = cat(3, C{:}); %// step 1
D = squeeze(mat2cell(D(1:N,:,:), N, size(C{1},2), ones(1,numel(C)))).'; %// steps 2 and 3

Upvotes: 1

Robert Seifert
Robert Seifert

Reputation: 25232

You were missing the definition of indices of the columns:

A = rand(10,2)
C = {A,A,A,A,A};

%//           here ....|
D = cellfun(@(x) x(1:5,:), C,'UniformOutput',false)

In this case you want all columns, that's why you use :. You could also use x(1:5,1:2) - in your case it's equal to x(1:5,:).


C = 

  Columns 1 through 5

    [10x2 double]    [10x2 double]    [10x2 double]    [10x2 double]    [10x2 double]


D = 

  Columns 1 through 5

    [5x2 double]    [5x2 double]    [5x2 double]    [5x2 double]    [5x2 double]

Upvotes: 2

Related Questions