choose row cell of matrix

2 ビュー (過去 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 Center および File ExchangeProgramming についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by