简体   繁体   中英

Replace certain elements of matrix with NaN (MATLAB)

I have a vector, A.

A=[3,4,5,2,2,4;2,3,4,5,3,4;2,4,3,2,3,1;1,2,3,2,3,4]

Some of the records in A must be replaced by NaN values, as they are inaccurate. I have created vector rowid, which records the last value that must be kept after which the existing values must be swapped to NaN.

rowid=[4,5,4,3]

So the vector I wish to create, B, would look as follows:

B=[3,4,5,2,NaN,NaN;2,3,4,5,3,NaN;2,4,3,2,NaN,NaN;1,2,3,NaN,NaN,NaN]

I am at a loss as to how to do this. I have tried to use

A(:,rowid:end)

to start selecting out the data from vector A. I am expecting to be able to use sub2ind or some sort of idx to do this, possibly an if loop, but I don't know where to start and cannot find an appropriate similar question to base my thoughts on!

I would very much appreciate any tips/pointers, many thanks

If you are not yet an expert of matlab, I would stick to simple for-loops for now:

B = A;
for i=1:length(rowid)
    B(i, rowid(i)+1:end) = NaN;
end

It is always a sport to write this as a one-liner (see Mohsen's answer), but in many cases an explicit for-loop is much clearer.

A compact one is:

B = A;
B(bsxfun(@lt, rowid.', 1:size(A,2)))=NaN;

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