简体   繁体   中英

Replacing only specific column values in an array in Matlab

I have an array that has about 70,000 rows that look like the following:

A = [ 1 2 3 4 5 6 0 723 1 22

      1 2 3 4 5 7 0 NaN 2 10 

      etc..                 ]

I would like to replace all NaN values in my array with the preceding value in the same column as the NaN value so that I would have something like this:

B = [ 1 2 3 4 5 6 0 723 1 22

      1 2 3 4 5 7 0 723 2 10 

      etc..                 ]

Since the array has about 70,000 rows, I am guessing some sort of loop would be the best way to achieve this. Using the following:

for ii = 1:size(A,2)
        I = A(1,ii);
        for jj = 2:size(A,1)
            if isnan(A(jj,ii))
                A(jj,ii) = I;
            else
                I  = A(jj,ii);
            end
        end
        end

I have been able to make a loop that replaces the whole row with the preceding row, but I am unsure how to modify it to target only NaN values. Any help would be greatly appreciated!

As long as there are now NaN 's in the first row, you can just replace the values directly:

for ii = 1:size(A,2)
    for jj = 2:size(A,1)
        if isnan(A(jj,ii))
            A(jj,ii) = A(jj-1,ii);
        end
    end
end

Which avoids creating a second matrix B .

I think you're right, an you do need to use for -loops since your matrix is so large, but here is a non- for loop version anyway:

while(any(isnan(A(:))))
    A(find(isnan(A)))=A(find(isnan(A))-1)
end

Not sure why the I = A(1, ii); or the else branch is needed. If a NaN is found, just replace it with the value from the previous row:

for ii = 1:size(A,2)
    for jj = 2:size(A,1)
        if (isnan(A(jj,ii)))
            A(jj,ii) = A(jj-1, ii); %jj-1 is the previous row
        end
    end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM