Find value in a cell array if you have its index
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Dimitris Kokkinos
il 6 Mag 2014
Risposto: Andrei Bobrov
il 6 Mag 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 Commenti
Risposta accettata
Andrei Bobrov
il 6 Mag 2014
n = cellfun(@numel,A);
ii = cumsum(n);
x = [A{:}];
out = x(B+[0;ii(1:end-1)]);
0 Commenti
Più risposte (1)
Azzi Abdelmalek
il 6 Mag 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 Commenti
Vedere anche
Categorie
Scopri di più su Resizing and Reshaping Matrices in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!