Find value in a cell array if you have its index
1 view (last 30 days)
Show older comments
Dimitris Kokkinos
on 6 May 2014
Answered: Andrei Bobrov
on 6 May 2014
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 Comments
Accepted Answer
Andrei Bobrov
on 6 May 2014
n = cellfun(@numel,A);
ii = cumsum(n);
x = [A{:}];
out = x(B+[0;ii(1:end-1)]);
0 Comments
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
0 Comments
See Also
Categories
Find more on Resizing and Reshaping Matrices 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!