User1961
User1961

Reputation: 131

MATLAB How to replace real values with NaN and NaN with real values

I have the following matrix

xx = [ 1 2 3 4; NaN NaN 7 8]; 

I want to change xx to be:

yy = [ NaN NaN NaN NaN; 88 88 NaN NaN];

I have the following script

for i = 1:2;
    for j = 1:4;
        if (xx(i,j) ~= NaN)
            yy(i,j) = NaN;
        else
            yy(i,j) = 88;
        end
    end
end
xx
yy

But I have the unwanted result, because

yy =

   NaN   NaN   NaN   NaN
   NaN   NaN   NaN   NaN

Thanks a lot for your help

Upvotes: 0

Views: 57

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112769

No need for loops. Just use logical indexing:

yy = xx; % initiallize yy to xx
ind = isnan(xx); % logical index of NaN values in xx
yy(ind) = 88; % replace NaN with 88
yy(~ind) = NaN; % replace numbers with NaN

Anyway, the problem with your code is that xx(i,j) ~= NaN always gives true. NaN doesn't equal anything, by definition. To check if a value is NaN you need the isnan function. So you should use ~isnan(xx(i,j)) in your code:

for i = 1:2;
    for j = 1:4;
        if ~isnan(xx(i,j))
            yy(i,j) = NaN;
        else
            yy(i,j) = 88;
        end
    end
end

Also, consider preallocating yy for speed. For example, you could initiallize yy with all entries equal to 88, and then you can remove the else branch:

yy = repmat(88, size(xx));
for i = 1:2;
    for j = 1:4;
        if ~isnan(xx(i,j))
            yy(i,j) = NaN;
        end
    end
end

Upvotes: 3

Related Questions