Extracting rows form a matrix with indices.

조회 수: 32 (최근 30일)
Paola
Paola 2023년 2월 21일
댓글: Paola 2023년 2월 23일
HI all,
i have a Matrix a=(24X30) and a vector b=(1,4,7,8,10,12) that represents the rows index. I would like to create a new Matrix C=(6X30). This matrix is composed of the 6 rows with indeces (1,4,7,8,10,12), the vector b.
How can I do that?
Thanks

채택된 답변

dpb
dpb 2023년 2월 21일
편집: dpb 2023년 2월 21일
M=[[1:24].' randi(100,24,5)]; % a sample array
b=[1,4,7,8,10,12]; % the indexing vector
N=M(b,:) % the new array
N = 6×6
1 57 8 36 5 76 4 84 18 83 22 27 7 5 28 43 98 24 8 46 27 91 59 88 10 2 98 51 46 36 12 91 21 100 33 33
illustrates vector indirect addressing does work.
NOTA BENE: the array M was created such that the first element is the row index value so can see which was selected by inspection to prove got what wanted...
  댓글 수: 2
dpb
dpb 2023년 2월 21일
M=[[1:24].' randi(100,24,5)]; % a sample array
b=[1,4,7,8,10,12]; % the indexing vector
ix=randperm(numel(b)) % let's shuffle them around...
ix = 1×6
5 4 2 3 1 6
N=M(b(ix),:)
N = 6×6
10 24 28 71 27 13 8 65 32 13 32 84 4 97 77 44 19 36 7 33 25 48 6 49 1 7 1 28 73 63 12 14 40 79 94 88
illustrates the addressing doesn't have to be in any specific order, either...
Paola
Paola 2023년 2월 23일
Thanks! It works

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

추가 답변 (1개)

Adam Drake
Adam Drake 2023년 2월 21일
% Create Matrix A: 24 x 30
A = randi(100,[24 30]);
% Create Vector B: desired row indices
B = [1,4,7,8,10,12];
% Create Matrix C: desired rows from Matrix A, specified by B
C = A(B,:);
The desired rows are specified by B, all columns are specified by ':'.

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by