كيفية حذف الصف والأعمد في أمر واحد من المصفوفة

조회 수: 2 (최근 30일)
sera
sera 2024년 10월 22일
댓글: Umar 2024년 10월 23일
How to delete row and column in one command of matrix in matlab ?

답변 (3개)

Bruno Luong
Bruno Luong 2024년 10월 22일
A = randi(9,5,6)
A = 5×6
1 9 1 7 9 8 8 5 5 4 9 7 8 8 2 4 9 1 4 7 8 4 6 2 7 5 1 6 7 7
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
rowremove = 3; colremove = 4;
B = A(setdiff(1:end,rowremove),setdiff(1:end,colremove))
B = 4×5
1 9 1 9 8 8 5 5 9 7 4 7 8 6 2 7 5 1 7 7
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

Walter Roberson
Walter Roberson 2024년 10월 22일
편집: Walter Roberson 2024년 10월 22일
YourMatrix(RowToDelete, :) = [];
YourMatrix(:, ColumnToDelete) = [];
Doing both as a single command would be tricky.

Umar
Umar 2024년 10월 22일

Hi @sera ,

In MATLAB, you can delete rows and columns from a matrix simultaneously by using logical indexing or by specifying the indices of the rows and columns you wish to remove. First, you need to define a matrix from which we want to delete specific rows and columns. Afterwards, identify which rows and columns we want to remove. This can be done by specifying their indices. Use the syntax matrix([rows_to_delete], :) = []; to delete the specified rows and matrix(:, [columns_to_delete]) = []; to delete the specified columns. However, to achieve both deletions in one command, you can combine these operations. Here is a complete MATLAB code snippet that demonstrates how to delete specific rows and columns from a matrix in one command:

% Step 1: Define the original matrix
A = [1, 2, 3, 4; 
   5, 6, 7, 8; 
   9, 10, 11, 12; 
   13, 14, 15, 16];
% Display the original matrix
disp('Original Matrix A:');
disp(A);
% Step 2: Specify the rows and columns to delete
rows_to_delete = [1, 3]; % Deleting the 1st and 3rd rows
columns_to_delete = [2, 4]; % Deleting the 2nd and 4th columns
% Step 3: Delete specified rows and columns in one command
A([rows_to_delete], :) = []; % Delete rows
A(:, [columns_to_delete]) = []; % Delete columns
% Display the final result
disp('Matrix A after deleting specified rows and columns:');
disp(A);

Please see attached.

Also, @Bruno Luong and @Walter Roberson has provided useful advice as well.

Hope this helps.

Please let us know if you have any further questions.

  댓글 수: 1
Umar
Umar 2024년 10월 23일
Hi @sera,
Please let us know if you still require any further assistance.

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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by