How to select the second element of each array of cells in a larger array of cells?

Enter

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

Supposed conclusion

11 22 33 44

Ps hhh{1}{2}, hhh{2}{2}, hhh{3}{2}and hhh{4}{2}returns the correct conclusion, but I am trying to find how to do it as hhh{:}{2}.

+4
source share
3 answers

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

For example:

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

Now extracting the second column has become trivial:

hhh(:,2)

The use of matrices is even worth considering if the data is not all the same length (but within reasonable limits), simply because they are stored more efficiently and processed so easily. Think of this example:

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

,

hhh(:,2)
+2

- cellfun

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

, , for.

, , , - , :

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

( , Matlab):

[hhh{:}](2:2:end)
+9

If the cells are guaranteed to be of equal length, you can use

cell2mat(vertcat(hhh{:}))*[0;1]

Multiplication selects the second column of the matrix, created by stacking arrays in cells.

EDIT:

for general case you can use

n=2;
result = cell2mat(vertcat(hhh{:}))*sparse(n,1,1,size(hhh{1},2),1);

or

temp = cell2mat(vertcat(hhh{:}));
result = temp(:,2);
+2
source

All Articles