choose row cell of matrix

조회 수: 1 (최근 30일)
NA
NA 2019년 1월 17일
편집: madhan ravi 2019년 1월 17일
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]}

채택된 답변

Stephen23
Stephen23 2019년 1월 17일
편집: Stephen23 2019년 1월 17일
A general solution in one line:
C = cellfun(@(r)A(r,:),B,'uni',0)

추가 답변 (2개)

madhan ravi
madhan ravi 2019년 1월 17일
편집: madhan ravi 2019년 1월 17일
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
madhan ravi
madhan ravi 2019년 1월 17일
편집: madhan ravi 2019년 1월 17일
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.

댓글을 달려면 로그인하십시오.


Guillaume
Guillaume 2019년 1월 17일
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

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by