To subset a matrix based on a condition in MATLAB, you can use logical indexing.
For example, let's say you have a matrix A
:
main.m27 chars2 lines
And you want to subset it based on the condition that the elements are greater than 4:
main.m14 chars2 lines
This will create a new matrix B
that contains only the elements of A
that are greater than 4.
If you want to keep the same shape of the original matrix, you can use the same logical indexing on both dimensions:
main.m46 chars3 lines
This will reshape the B
matrix to have the same shape as the elements in A
that meet the condition.
You can also use logical indexing to subset rows or columns of a matrix.
For example, to subset only the rows of A
that contain a value greater than 4:
main.m25 chars2 lines
This will create a new matrix B
that contains only the rows of A
that have at least one value greater than 4.
Similarly, to subset only the columns of A
that contain a value greater than 4:
main.m22 chars2 lines
This will create a new matrix B
that contains only the columns of A
that have at least one value greater than 4.
gistlibby LogSnag