MATLAB: Is there a way to convert all values of NaN to zero over the entire workspace

nannan to 0nan to 0 for all arrays

I have a workspace with many arrays, many of which have NaN components. I know you can convert all NaN in a single array to be 0, but is there a way to convert all NaN in each array in the workspace to be zero without manual going through each array?

Best Answer

Try the whos function to get a list of variable names, then use eval to set their nans to zero.
% Sample data
v1 = [0 0 1 1 0 nan 0 1] % Array with nan

v2 = [0,0,1,1,0,nan,0,1,1,1] % Array with nan
str = 'abcdef'; % Non numerical array
% Get a list of all variables.
s = whos
for k = 1 : length(s)
commandLine = sprintf('%s(isnan(%s))=0', s(k).name, s(k).name)
eval(commandLine)
end
% Let's see if it worked
v1
v2
str % Hopefully it didn't do anything with this variable.