extract all rows of a matrix except 'r' (vector) rows

조회 수: 18 (최근 30일)
Alberto Acri
Alberto Acri 2023년 9월 8일
답변: MarKf 2023년 9월 8일
Hi! I need to extract all rows of 'matrix' except 'r' rows.
matrix = [54; 55; 56; 57; 58; 59; 60; 61; 62; 63; 64; 65];
r = [1; 2; 3; 4: 9];
The result is:
matrix_out = [58; 59; 60; 61; 63; 64; 65];

채택된 답변

Stephen23
Stephen23 2023년 9월 8일
The most efficient approach:
matrix = [54; 55; 56; 57; 58; 59; 60; 61; 62; 63; 64; 65];
r = [1; 2; 3; 4; 9];
matrix_out = matrix;
matrix_out(r) = []
matrix_out = 7×1
58 59 60 61 63 64 65

추가 답변 (2개)

Dyuman Joshi
Dyuman Joshi 2023년 9월 8일
편집: Dyuman Joshi 2023년 9월 8일
matrix = [54; 55; 56; 57; 58; 59; 60; 61; 62; 63; 64; 65];
r = [1; 2; 3; 4; 9];
%Method 1
%remove directly
matrix(r,:)=[];
%or
%Method 2
%remove indirectly
idx = 1:size(matrix,1);
ix = setdiff(idx,r);
matrix = matrix(ix,:);
Note that Method 1 won't work when there is an index not in the range of the dimensions of the array matrix.
For such cases, use Method 2.

MarKf
MarKf 2023년 9월 8일
mat = magic(8)
mat = 8×8
64 2 3 61 60 6 7 57 9 55 54 12 13 51 50 16 17 47 46 20 21 43 42 24 40 26 27 37 36 30 31 33 32 34 35 29 28 38 39 25 41 23 22 44 45 19 18 48 49 15 14 52 53 11 10 56 8 58 59 5 4 62 63 1
r_not = [1 3:5 8];
mat(r_not,:) = [] %use mat_o = mat; to keep the original mat;
mat = 3×8
9 55 54 12 13 51 50 16 41 23 22 44 45 19 18 48 49 15 14 52 53 11 10 56
There are some issues with your example:
matrix = [54; 55; 56; 57; 58; 59; 60; 61; 62; 63; 64; 65];
r = [1:3, 6, 9]; %btw this did not work with those dimensions;
% also not the way you wanted with those indices (matrix_out just removed 1:3)
matrix_out = matrix;
matrix_out(r,:) = []
matrix_out = 7×1
57 58 60 61 63 64 65
Since yours is a simple vector, matrix_out(r) = []; would have worked easily too

카테고리

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

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by