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

5 visualizaciones (últimos 30 días)
sera
sera el 22 de Oct. de 2024
Comentada: Umar el 23 de Oct. de 2024
How to delete row and column in one command of matrix in matlab ?

Respuestas (3)

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

Umar
Umar el 22 de Oct. de 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 comentario
Umar
Umar el 23 de Oct. de 2024
Hi @sera,
Please let us know if you still require any further assistance.

Iniciar sesión para comentar.

Categorías

Más información sobre Programming en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by