subsetting matrix based on a condition in matlab

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.m
A = [1 2 3; 4 5 6; 7 8 9];
27 chars
2 lines

And you want to subset it based on the condition that the elements are greater than 4:

main.m
B = A(A > 4);
14 chars
2 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.m
B = A(A > 4);
B = reshape(B, size(A(A > 4)));
46 chars
3 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.m
B = A(any(A > 4, 2), :);
25 chars
2 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.m
B = A(:, any(A > 4));
22 chars
2 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