Find value in a cell array if you have its index
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Dimitris Kokkinos
am 6 Mai 2014
Beantwortet: Andrei Bobrov
am 6 Mai 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 Kommentare
Akzeptierte Antwort
Andrei Bobrov
am 6 Mai 2014
n = cellfun(@numel,A);
ii = cumsum(n);
x = [A{:}];
out = x(B+[0;ii(1:end-1)]);
0 Kommentare
Weitere Antworten (1)
Azzi Abdelmalek
am 6 Mai 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 Kommentare
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!