[英]How can I convert a cell array to numerical array in Matlab?
I have read some data from an Excel file in Matlab. 我已经从Matlab中的Excel文件中读取了一些数据。 A cell array has been generated as follow: 单元格数组已生成如下:
x={'11', 'NaN', 'NaN', '13', 24}
I want to convert cell array to a numeric matrix (for other required calculations) and convert 'NaN' elements to zero in my numeric matrix. 我想将单元格数组转换为数值矩阵(用于其他所需的计算),并在数字矩阵中将“ NaN”元素转换为零。 How can I do it? 我该怎么做?
Thank you. 谢谢。
You can use str2double
to convert strings to numeric values: 您可以使用str2double
将字符串转换为数值:
x={'11', 'NaN', 'NaN', '13', '24'};
nx = str2double(x);
Once you have numeric values, you can substitute the nan
s with zeros: 获得数值后,可以将nan
替换为零:
nx(isnan(nx))=0
In the example you gave in the question there is a mixed content (strings and numbers), so it takes 2 steps: 在您输入的问题示例中,内容混合(字符串和数字),因此需要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
Then you can replace all NaN
s with zeros: 然后,您可以将所有NaN
替换为零:
numx(isnan(numx)) = 0;
the result: 结果:
numx =
11 0 0 13 24
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.