Find value in a cell array if you have its index
Show older comments
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
Accepted Answer
More Answers (1)
Azzi Abdelmalek
on 6 May 2014
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
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!