Search code examples
matlabcell-array

How do I replace an element from a cell array?


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?


Solution

  • 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.