choose row cell of matrix

2 次查看(过去 30 天)
NA
NA 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 中查找有关 Environment and Settings 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by