0

Hi I have two arrays,

A = [23 Nan 45 Nan Nan 67 50 100 110] and B = [24 49 70 71 72 90 100 120 109]

NaN denotes some gap. I want to place the element of matrix B in the same location in A where it is NaN. For example, in array A 2nd position there is a gap, I want to put value 49 from matrix B into that position in array A. So the resulting A matrix becomes

A = [23 49 45 71 72 67 50 100 110]

Let me know how I can code it in MATLAB. Thanks,

2
  • I'm not sure how you have a string (x) in a numeric array in Matlab. Commented Aug 8, 2015 at 17:41
  • that is only to show missing value. It's a null. Instead of NaN, I put x in that place. Commented Aug 8, 2015 at 17:45

1 Answer 1

2

You can do this very easily using array indexing.

A = [23 NaN 45 NaN NaN 67 50 100 110]
B = [24 49 70 71 72 90 100 120 109]
all_nans = isnan(A)
A(all_nans) = B(all_nans)

Giving:

A =

    23    49    45    71    72    67    50   100   110

all_nans contains the indices of all the NaNs and the next step basically does the required replacement.

Sign up to request clarification or add additional context in comments.

1 Comment

It's worth pointing out that while you can also do A(isnan(A)) = B(isnan(A)), you can not do A(A == NaN) = B(A == NaN) like you would be able to do with -1 (or any other number), since NaN does not equal NaN.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.