Create a matrix using the following code:
A = [1:4; 5:8; 9:12];
A = 1 2 3 4 5 6 7 8 9 10 11 12
To delete items from a matrix, assign to the target an empty array. After the deletion, the items that followed the target are moved to occupy the vacated spot. You can use linear, subscript or logical indices to reference the target.
% Delete the third column A(:,3) = ;
A = 1 2 4 5 6 8 9 10 12
% Delete the second row A(2,:) = ;
A = 1 2 4 9 10 12
% Delete the first item A(1) = ;
A = 9 2 10 4 12
% Delete the items greater than 7 A(A>7) = ;
A = 2 4
Note: If you use linear or logical indices, the result is a row vector. If an index is out of range, MATLAB generates an error.
I recommend the following books to learn more on matrix manipulation in MATLAB.
This book was the winner of a Textbook Excellence Award. The second chapter explains how to perform a wide list of operations on matrices, including deleting items.
MATLAB for Engineers (5th Edition)
This excellent book is especially oriented to engineers and scientists who want to learn MATLAB programming. Matrix manipulation is explained in the fourth chapter.
I also recommend the other tutorials in this series.
- How to Get the Size of a Matrix in MATLAB
- How to Get the Number of Elements in a Matrix in MATLAB
- How to Get the Number of Dimensions of a Matrix in MATLAB
- How to Reshape a Matrix in MATLAB
- How to Delete Items From a Matrix in MATLAB
- How to Transpose a 2D Matrix in MATLAB
- How to Transpose a Multidimensional Matrix in MATLAB
- How to Reverse a 2D Matrix in MATLAB
- How to Reverse a Multidimensional Matrix in MATLAB
Consult the help documentation of the
rand function. Create a matrix of random numbers having five rows and four columns.
- Delete the fourth column
- Delete the last two rows
- Delete the items lower than 0.5
- Delete the second item, if it exists
A possible solution could be:
doc rand; X = rand(5,4); % Clause 1 X(:,4) = ; % Clause 2 X(4:5,:) = ; % Clause 3 X(X<0.5) = ; % Clause 4 X(2) = ; % Clause 4 (a better way) if(numel(X) >= 2) X(2) = ; end
I hope you have learned how to delete items from a matrix in MATLAB. The source code developed in this tutorial is available at this page.