3

If I have a cell array like this:

>> mycellarray = [{'Country' 'State' '1/22/01' '1/23/01' '1/24/01'};{'Afghanistan' '' [0 0] [0 1] [0 2]}]
mycellarray =
 2×5 cell array
{'Country'    }    {'State' }    {'1/22/01'}    {'1/23/01'}    {'1/24/01'}
{'Afghanistan'}    {0×0 char}    {[    0 0]}    {[    0 1]}    {[    0 2]}

I can retrieve all the data values I need using:

>> myvals = mycellarray(2,3:5)
myvals =
 1×3 cell array
 {[0 0]}    {[0 1]}    {[0 2]}

I would like to extract the 2nd element in each vector, so I would get a vector back like this:

[0 1 2]

How would I do that?

1
  • You might want to use a table for these data. Commented Jul 29 at 17:30

1 Answer 1

5

You could do this with an intermediate step to stack all of the 2-element arrays, then extract the 2nd column

v = vertcat(mycellarray{2,3:5});
myvals = v(:,2).';

The .' is a transpose to get a row vector as in your question, if a column is OK then you can omit this

If you particularly want a one-liner or to skip the intermediate matrix, you could use cellfun to loop over the sub-cell of elements you want and pick the 2nd element in each:

myvals = cellfun( @(x) x(2), mycellarray(2,3:5) );
Sign up to request clarification or add additional context in comments.

Comments

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.