Logical Indexing

LogicalIndexing is a language construct in MatLab that creates a view into a matrix, which can be extracted or modified.

Example:

A(A == 3) = 5;

This statement has the following effect: The inner part, A == 3, is evaluated like any normal matrix expression, resulting in a matrix containing logical values whose element is true if the corresponding element in A equals 3, false otherwise. When this expression is used to index A, namely A(logical_expr), it becomes a view into the matrix selecting the elements for which the corresponding logical element is true.

Consider the following:

data = ... % some data source resulting in a cell array rowMatches = strcmp(data(:, colName), nameToFind); % a column vector of logical values, true if matching nameToFind data(rowMatches, colTelephone) = phoneToReplace; % for rows that match, replace the row's value in the telephone column.


EditText of this page (last edited December 17, 2011) or FindPage with title or text search