【问题标题】:How can I convert a cell array to numerical array in Matlab?如何在 Matlab 中将单元格数组转换为数值数组?
【发布时间】:2017-05-22 16:17:41
【问题描述】:

我从 Matlab 中的 Excel 文件中读取了一些数据。一个元胞数组已生成如下:

x={'11', 'NaN', 'NaN', '13', 24}

我想将元胞数组转换为数值矩阵(用于其他所需的计算)并将我的数值矩阵中的“NaN”元素转换为零。我该怎么做?

谢谢。

【问题讨论】:

    标签: arrays excel matlab cell nan


    【解决方案1】:

    您可以使用str2double 将字符串转换为数值:

    x={'11', 'NaN', 'NaN', '13', '24'};
    nx = str2double(x);
    

    一旦你有了数值,你可以用零替换nans:

    nx(isnan(nx))=0
    

    【讨论】:

    • @Yaser,如果输入与问题中的一样,这将不起作用 - 最后一个值 (24) 是数字,而不是字符串。请参阅my answer 来处理这个问题。
    【解决方案2】:

    在您在问题中给出的示例中,存在混合内容(字符串和数字),因此需要 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-14
      • 1970-01-01
      • 1970-01-01
      • 2021-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多