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

46 次查看(过去 30 天)
sera
sera 2024-10-22,18:18
评论: Umar 2024-10-23,13:03
How to delete row and column in one command of matrix in matlab ?

回答(3 个)

Bruno Luong
Bruno Luong 2024-10-22,20:10
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,19:50
编辑:Walter Roberson 2024-10-22,19:52
YourMatrix(RowToDelete, :) = [];
YourMatrix(:, ColumnToDelete) = [];
Doing both as a single command would be tricky.

Umar
Umar 2024-10-22,23:53

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,13:03
Hi @sera,
Please let us know if you still require any further assistance.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by