exclude nan values in a vector in matlab

You can exclude NaN values from a vector in matlab using logical indexing. The code below demonstrates how to achieve this:

main.m
% Example vector
v = [1 2 NaN 4 5 NaN];

% Remove NaN values
v_without_nan = v(~isnan(v));
91 chars
6 lines

The isnan(v) returns a logical array with 1's at the locations of NaN values in the vector v. The ~ symbol negates this logical array and returns a logical array with 1's at locations of non-NaN values in the vector v. Finally, the logical array is used to index the original vector to remove the NaN values. The resulting vector is stored in v_without_nan.

Note that the logical index should be of the same size as the vector being indexed. To avoid this issue, the code can be modified as follows:

main.m
% Example vector
v = [1 2 NaN 4 5 NaN];

% Remove NaN values
v_without_nan = v;
v_without_nan(isnan(v)) = [];
110 chars
7 lines

Here, we first create a new variable called v_without_nan which is a copy of the original vector. Then we use isnan(v) as the index of the logical array to delete the elements from v_without_nan that correspond to NaN values in the original vector v

related categories

gistlibby LogSnag