1

I have a cell array of size 1x84, where the elements are 1x1 or 1x2 cells.

I woluld like to get a cell array of size 1x84 by taking the first element from the nested cells

CellList = <1x84 cell>

CellList  = <1x1 cell>  <1x1 cell>  <1x1 cell>  <1x2 cell>  <1x1 cell> ... <1x2 cell>       

The subelements are also cells


I tried using this code:

CellList = cellfun(@(x)x{1,:}{1,:},CellList, 'UniformOutput',0);

But I faced the following error:

error : Cell contents reference from a non-cell array object.

1 Answer 1

2

cellfun accesses each element of the cell you give it, so you are taking an element x, trying to access its first element, and the first element of that which doesn't exist.

You want to use

CellList2 = cellfun(@(x)x{1}, CellList, 'uniformoutput', false)

Edit:

You claim you're still getting an error, in which case your problem is not reproducible. Here is some setup code:

% define a 1x84 cell array
c = cell(1,84);
% Make each element a 1x2 or 1x1 cell array 
for n = 1:84; c{n} = cell(1,randi([1,2],1)); end;
% Output is as you've described and shown
>> c = <1x84 cell>
     = <1x2 cell> <1x1 cell> <1x1 cell> ... <1x2 cell>

Now use my above code, and it works fine.

d = cellfun(@(x)x{1},c,'uniformoutput',false);
d = <1x84 cell>
  = [] [] [] [] ... []   % All empty elements as we initialised empty cells
Sign up to request clarification or add additional context in comments.

4 Comments

error : Cell contents reference from a non-cell array object. still the same error
Then please post example code (in a question edit) which generates an equivalent cell array to use for testing... for example are the sub-elements actually cells or just normal matrices?
for i = 1:84 c{i} = c{i}(1); end Above code has solved my issue in very short method. Sorry, if my question confused. I feel what u have explained is very complex in my requirement.
What is that supposed to mean?

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.