Search code examples
matlabcell-array

How to choose the second element of each cell-array in a larger cell-array?


Input

hhh={{1,11},{2,22},{3,33},{4,44}}

Intended output

11 22 33 44

P.s. hhh{1}{2}, hhh{2}{2}, hhh{3}{2} and hhh{4}{2} returns the right output but I am trying to find how to do it like hhh{:}{2}.


Solution

  • If your array is guaranteed to be square and numeric, you should seriously consider using a matrix instead.

    For example:

    hhh=[1, 11; 2, 22 ;3, 33; 4, 44]
    

    Now extracting the second column has become trivial:

    hhh(:,2)
    

    Using matrices is even worth considering if the data is not all of equal length (but within reasonable variation), simply because it stores more efficiently and handles so easily. Think about this example:

    hhh=[1, 11, 111; 2, 22, 222 ;3, 33, NaN; 4, 44, 444]
    

    Now it is still as easy as

    hhh(:,2)