choose row cell of matrix

1 vue (au cours des 30 derniers jours)
NA
NA le 17 Jan 2019
Modifié(e) : madhan ravi le 17 Jan 2019
I have
A=[1 2 0.1 0.2;...
1 5 0.2 0.2;...
2 3 0.4 0.4;...
2 4 0.9 0.8;...
2 5 0.3 0.4;...
3 4 1.1 2.2]
and
B={[1,2,5],[3,4,6]}
I want to get a C that rows of it, is B and column of it is all column of A
C=cell(1, size(B,2));
for i=1:length(B)
for j=1:length(B{i})
C{i}(j)=A(j,:)
end
end
I want this result
C={[1 2 0.1 0.2 ;...
1 5 0.2 0.2 ;...
2 5 0.3 0.4],...
[2 3 0.4 0.4 ;...
2 4 0.9 0.8 ;...
3 4 1.1 2.2]}

Réponse acceptée

Stephen23
Stephen23 le 17 Jan 2019
Modifié(e) : Stephen23 le 17 Jan 2019
A general solution in one line:
C = cellfun(@(r)A(r,:),B,'uni',0)

Plus de réponses (2)

madhan ravi
madhan ravi le 17 Jan 2019
Modifié(e) : madhan ravi le 17 Jan 2019
A=[1 2 0.1 0.2;...
1 5 0.2 0.2;...
2 3 0.4 0.4;...
2 4 0.9 0.8;...
2 5 0.3 0.4;...
3 4 1.1 2.2];
B={[1,2,5],[3,4,6]};
C{1}=A(B{1},:);
C{2}=A(B{2},:);
celldisp(C)
Gives:
C{1} =
1.0000 2.0000 0.1000 0.2000
1.0000 5.0000 0.2000 0.2000
2.0000 5.0000 0.3000 0.4000
C{2} =
2.0000 3.0000 0.4000 0.4000
2.0000 4.0000 0.9000 0.8000
3.0000 4.0000 1.1000 2.2000
  1 commentaire
madhan ravi
madhan ravi le 17 Jan 2019
Modifié(e) : madhan ravi le 17 Jan 2019
Just use it in a loop then?
C=cell(1,numel(B));
for j=1:numel(B)
C{j}=A(B{j},:);
end
celldisp(C)
Note: It's the one that Guillaume has suggested as the second option.

Connectez-vous pour commenter.


Guillaume
Guillaume le 17 Jan 2019
C = cellfun(@(rows) A(rows, :), B, 'UniformOutput', false)
or if you prefer a loop:
C = cell(size(B));
for idx = 1:numel(B)
C{idx} = A(B{idx}, :);
end

Catégories

En savoir plus sur Programming dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by