フィルターのクリア

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

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

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by