Access predefined elements of cells

笑着哭i 提交于 2019-12-06 07:13:17

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))
Werner

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