Access Predefined Cell Elements

I have an array of cells A [1x80], in which each element is the array of cells [9x2] itself. I also have a vector B representing a group of selected cells A, and I want to extract the {2,2} element of each selected cell.

I tried with simple

A (1, B) {2.2}

but of course this does not work. Can you help me?

+2
source share
3 answers

How about this:

A = {{1 2; 3 4}, {5 6;7 8}, {9 0; 1 2}; {3 4; 5 6}, {7 8; 9 0}, {11 22; 33 44}}; B = [2,3] [cellfun(@(x)x(2,2), A){1, B}] ans = 8 2 

EDIT:

The above actually only works in an octave. As @Amro points out, in order to change it to work in Matlab, you need to use a temporary variable:

 temp = cellfun(@(x)x(2,2), A); [temp{1, B}] 

or in one insert (also thanks to @Amro)

 cellfun(@(c)c{2,2}, A(1,B)) 
+3
source

This answer is the same as @Dan, but if necessary uses a simple loop to improve performance.

 % If you know that the numel of elements returned by {2,2} will always be one: nElem = numel(B); ret(1,nElem)=0; for k=1:nElem ret(k) = A{1,B(k)}{2,2} end 

The following answer is incorrect, it will return the index {2,2} from the first element from B

 subsref([A{1,B}],struct('type','{}','subs',{{2,2}})) 

Which is more like what you are doing (and not using cellfun and arrayfun , it would be better if you perform this operation in a loop because they are slow )

See the subsref documentation here .

Longer way:

 temp = [A{1,B}] temp{2,2} 
+2
source

Source: https://habr.com/ru/post/1498421/


All Articles