set all values in a matrix which equal nan to zero in matlab

You can use the isnan function to create a logical matrix of the same size as your matrix. The isnan function returns a matrix of 1's where the input is NaN and 0's everywhere else. You can then use this logical matrix to set the elements of your matrix that are NaN to zero.

Here's an example:

main.m
A = [1 2 NaN; 3 NaN 4; NaN 5 6];

nan_logical = isnan(A);

A(nan_logical) = 0;
79 chars
6 lines

In this example, we create a 3x3 matrix A with some NaN values. We then create a logical matrix nan_logical that is true where A is NaN. Finally, we use the logical matrix to set the NaN values to 0 in A.

You can also accomplish this in a single line by combining the isnan and indexing operations:

main.m
A(isnan(A)) = 0;
17 chars
2 lines

This will have the same effect as the previous example.

related categories

gistlibby LogSnag