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

13 次查看(过去 30 天)
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 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by