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

5 visualizzazioni (ultimi 30 giorni)
sera
sera il 22 Ott 2024
Commentato: Umar il 23 Ott 2024
How to delete row and column in one command of matrix in matlab ?

Risposte (3)

Bruno Luong
Bruno Luong il 22 Ott 2024
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 il 22 Ott 2024
Modificato: Walter Roberson il 22 Ott 2024
YourMatrix(RowToDelete, :) = [];
YourMatrix(:, ColumnToDelete) = [];
Doing both as a single command would be tricky.

Umar
Umar il 22 Ott 2024

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 Commento
Umar
Umar il 23 Ott 2024
Hi @sera,
Please let us know if you still require any further assistance.

Accedi per commentare.

Categorie

Scopri di più su Programming in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by