How do I replace an element from a cell array?

牧云@^-^@ 提交于 2019-12-20 05:45:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!