Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}.

like image 847
hhh Avatar asked Dec 12 '22 10:12

hhh


1 Answers

One way would be to use cellfun

n=2
cellfun(@(x)(x{n}), hhh)

Which is essentially just a short hand for a for loop.

Or another possibly which is completely vectorized but will be more difficult to generalize is to first linearize and then select every second element:

temp = [hhh{:}]
[temp{2:2:end}]

Octave allows this in one line (Matlab does not unfortunately):

[hhh{:}](2:2:end)
like image 67
Dan Avatar answered Jan 18 '23 04:01

Dan