Access predefined elements of cells

冷暖自知 提交于 2019-12-10 10:57:45

问题


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

I tried with a simple

A(1,B){2,2}

but of course it doesn't work.... Can you help me?


回答1:


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 octave. As @Amro points out, to modify it to work in Matlab you need to use a temporary variable:

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

or in a one liner (also thanks to @Amro)

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



回答2:


This answer is the same as @Dan's, but using a simple for loop for performance improvement, if needed.

% 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 wrong, it will only return the {2,2} index from the first element from B

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

Which sounds more like what you are doing (and doesn't uses cellfun and arrayfun, that would be better if you are doing this operation on a loop, because they are slow)

See subsref documentation here.

A longer path would be:

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



回答3:


How about arrayfun(@(x) A{1,x}{2,2}, B)
or (thanks @Amro) cellfun(@(c)c{2,2}, A(1,B))?



来源:https://stackoverflow.com/questions/18381366/access-predefined-elements-of-cells

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!