Find value in a cell array if you have its index
조회 수: 3 (최근 30일)
이전 댓글 표시
I have a cell array which has vectors as cells.I have an array containing some indices.I need from that indices to find the corresponding values of the cell array.For example
A{1,1}=[35,9,45,7];
A{2,1}=[21,4,65,3,11];
A{3,1}=[14,32];
and
B=[2;5;1];
I need to get
C=[9;11;14]
Which is the faster way?
my suggestion is
for ia=1:lenght(A)
C=A{ia}(B(ia));
end
댓글 수: 0
채택된 답변
Andrei Bobrov
2014년 5월 6일
n = cellfun(@numel,A);
ii = cumsum(n);
x = [A{:}];
out = x(B+[0;ii(1:end-1)]);
댓글 수: 0
추가 답변 (1개)
Azzi Abdelmalek
2014년 5월 6일
You can use
C1=cellfun(@(x,ii) x(ii),A,num2cell(B))';
But your for loop is faster, do not forget the pre-allocation
C2=zeros(1,numel(B));
for ia=1:numel(B)
C2(1,ia)=A{ia}(B(ia));
end
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!