【发布时间】:2017-05-22 16:17:41
【问题描述】:
我从 Matlab 中的 Excel 文件中读取了一些数据。一个元胞数组已生成如下:
x={'11', 'NaN', 'NaN', '13', 24}
我想将元胞数组转换为数值矩阵(用于其他所需的计算)并将我的数值矩阵中的“NaN”元素转换为零。我该怎么做?
谢谢。
【问题讨论】:
标签: arrays excel matlab cell nan
我从 Matlab 中的 Excel 文件中读取了一些数据。一个元胞数组已生成如下:
x={'11', 'NaN', 'NaN', '13', 24}
我想将元胞数组转换为数值矩阵(用于其他所需的计算)并将我的数值矩阵中的“NaN”元素转换为零。我该怎么做?
谢谢。
【问题讨论】:
标签: arrays excel matlab cell nan
您可以使用str2double 将字符串转换为数值:
x={'11', 'NaN', 'NaN', '13', '24'};
nx = str2double(x);
一旦你有了数值,你可以用零替换nans:
nx(isnan(nx))=0
【讨论】:
在您在问题中给出的示例中,存在混合内容(字符串和数字),因此需要 2 个步骤:
x = {'11', 'NaN', 'NaN', '13', 24}; % last value is a number
isch = cellfun(@isstr,x); % find all strings
numx(isch) = str2double(x(isch)); % convert the strings to numbers, and place the correcly
numx(~isch) = cell2mat(x(~isch)); % extract the numbers and place the correcly
然后你可以用零替换所有NaNs:
numx(isnan(numx)) = 0;
结果:
numx =
11 0 0 13 24
【讨论】: