简体   繁体   English

如何在Matlab中将单元格数组转换为数值数组?

[英]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.

相关问题 如何在MATLAB中将单元格数组转换为数值数组? - How can I convert a cell array into a numeric array in MATLAB? 如何将单元格数组中的字符串转换为数字替代值? - How to convert strings in a cell array to numerical stand-in values? 在MatLab中,如何从单元格数组创建字符向量? - In MatLab, how can I create a character vector from a cell array? 如何将Matlab单元格字符串数组转换为.NET字符串数组 - How to convert Matlab cell string array to .NET string array 如何在 MATLAB 中将二维矩阵元胞数组转换为多维数组 - How to convert a cell array of 2D matrices into a multidimensional array in MATLAB 我如何在一个矩阵中的一个单元的另一个单元中的一个单元中存储3个元素 - How I can store 3 element from one array at the one cell in another array in matlab 如何将元胞数组中的元素保存到 matlab 中的普通数组中 - How can i save an element from a cell array into a normal array in matlab 如何在Matlab中将具有不同数据格式的单元格数组转换为矩阵? - How do I convert a cell array w/ different data formats to a matrix in Matlab? 如何在MATLAB中将矩阵的单元格数组转换为列矩阵? - How to convert cell array of matrices into a column matrix in MATLAB? Matlab:将单元格的单元格数组转换为单个单元格数组 - Matlab: Convert cell array of cells into a single cell array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM