如何替换单元格数组中的元素? [英] How do I replace an element from a cell array?

查看:88
本文介绍了如何替换单元格数组中的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单元格数组:

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

我想用NaNs代替A的第三个元素,以获得

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?

推荐答案

您可以创建一个所有NaN的新数组,然后用初始单元格数组中的值替换第三个元素

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.

这篇关于如何替换单元格数组中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆