0

I have a cell array:

A = {NaN, ‘k’, ‘m’, ‘n’}

I want to replace all but the 3rd element of A with NaNs to obtain

B = {NaN, NaN, ‘m’, NaN}

Please, any help/suggestions on how I could go about this? Also, is it possible to do this with a single line of code?

4
  • Can you be a bit more specific? how general should the solution be? Do you have an array of integers that contain the indices of the elements that should be replaced with NaNs or how do you know which elements should be replaced? Commented Feb 9, 2017 at 14:12
  • Why are you using double NaN's in combination with characters? weird combination to me Commented Feb 9, 2017 at 14:17
  • Good question @julian59189. I actually couldn't think of a better way to state the problem as the main code is a bit cumbersome and might take some pain to understand - hence i decided to make the question simple and hope that i would get an answer that i could adapt. For the last part of your question, a couple of 'IF' statements are to decide the particular element to be replaced. Not to worry though, Suever's 2nd solution is ideal for me. Thanks! Commented Feb 9, 2017 at 14:38
  • @J.H.Bonarius, weird combination indeed, but it does serve the purpose. Commented Feb 9, 2017 at 14:47

1 Answer 1

1

You could create a new array of all NaN's and then replace the third element with the value from the initial cell array

B = num2cell(nan(size(A));
B(3) = A(3);

Alternately, you can overwrite the other values with:

B = A;
B([1 2 4]) = {NaN};

As far as a single line of code, the number of lines is quite irrelevant. What's important is readability and performance. These two things are not necessarily correlated with the number of lines.

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

3 Comments

deal is not necessary. I think B([1:2 4:end]) = {NaN} is better. No?
@Sardar_Usama Ah yes. If you rely on comma-separated values on the left it is necessary but the () assignment is a better option. Thanks
Many thanks @Suever. Works perfectly (the 2nd code suits me more). Actually i have the cell array as a p x 4 matrix in which case i am to perform certain task by looping through the array row-wise. Hence, i had to add the number of rows to your code as: [B{p, [1 2 4]}] = deal(NaN); and i was surprised it still worked.

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.