问题
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?
回答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.
来源:https://stackoverflow.com/questions/42138886/how-do-i-replace-an-element-from-a-cell-array