ff.ford1
ff.ford1

Reputation: 33

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

Upvotes: 3

Views: 3899

Answers (2)

Mohsen Nosratinia
Mohsen Nosratinia

Reputation: 9864

A compact one is:

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

Upvotes: 2

Bas Swinckels
Bas Swinckels

Reputation: 18488

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.

Upvotes: 2

Related Questions