【问题标题】:MATLAB: Remove Inf or NaNMATLAB:删除 Inf 或 NaN
【发布时间】:2017-07-13 11:21:41
【问题描述】:

如果我有一个包含-InfInfNaN 条目的结构,我想将它们替换为0 或空。这可能吗?如果可以,如何实施?它还需要适用于嵌套数据。

Isinf()isnan() 不能用于结构数组。

例子:

test(1).a = 1;
test(2).a = Inf;
test(1).b = NaN;
test(2).b = 2;

但是,字段名可以是任何东西,并且应该被假定为未知。这个结构打印出来是这样的:

a b 1 1 NaN 2 Inf 2 

我希望它是:

a b 1 1 0 2 0 2

【问题讨论】:

标签: arrays matlab object structure


【解决方案1】:

假设您的结构不包含任何要递归的子结构,并且您只想找到InfNaN标量 值并将它们替换为0 或[] ,以下是您可以轻松做到这一点的方法:

s = struct('a', {1, Inf}, 'b', {NaN, 2});  % Sample data

f = fieldnames(s);   % Get field names
c = struct2cell(s);  % Convert structure to a cell array
[c{cellfun(@(d) isnumeric(d) && isscalar(d) && ~isfinite(d), c)}] = deal(0);
s = cell2struct(c, f, 1);  % Rebuild structure array

还有输出:

s(1)

ans = 
  struct with fields:
    a: 1
    b: 0

s(2)

ans = 
  struct with fields:
    a: 0
    b: 2

如果您希望有空字段而不是零,则可以将 deal(0) 替换为 deal([])

它是如何工作的......

函数fieldnamesstruct2cell 首先用于将结构体数组转换为字段名称fcell array 和字段内容c 的元胞数组。这将更容易使用。

接下来,cellfun 用于将anonymous function 应用于c 的每个单元格。该函数首先检查numeric values,然后检查它们是否为scalar matrices,最后检查它们是否不是finite。这将返回一个logical array(对于找到标量InfNaN 值的单元格,使用true)用于索引c 并使用deal 分配值0。

最后,使用cell2struct重构结构体数组,f中的原始字段名称和c中的修改后的字段内容。

【讨论】:

    【解决方案2】:

    解决方案

    使用 MATLAB 的 isnan 和 isinf 函数如下:

    mat(isinf(mat) | isnan(mat)) = 0;
    

    示例

    %defines input matrix
    mat = rand(3,3); mat(1,1) = nan;
    mat(2,3) = inf;mat(2,2) = -inf;
    
    %replaces nans and infs with zeros
    mat(isinf(mat) | isnan(mat)) = 0;
    

    结果

    mat =
    
    0    0.0357    0.6787
    0.9595         0         0
    0.6557    0.9340    0.7431
    

    【讨论】:

    • 这是我之前遇到的一个问题;您的方法适用于元胞数组,但对于结构数组则不可能,因为它会引发错误:未定义函数 'isinf' for input arguments of type 'struct'。
    • 请提供一个简单的结构格式示例,以便我们知道如何访问您的值!
    • test(1).a = 1 test(2).a = Inf test(1).b = NaN test(2).b = 2 但是字段名可以是任何东西,应该是假定为未知。这个结构打印出来是这样的: a b 1 1 NaN 2 Inf 2 我希望它是: a b 1 1 0 2 0 2
    • 抱歉,stackoverfow 删除了换行符,因此格式混乱
    • @Seb 编辑您的原始问题并添加您的示例
    猜你喜欢
    • 2017-04-13
    • 2012-11-08
    • 2013-03-24
    • 2018-01-26
    • 2016-08-15
    • 2021-11-29
    • 1970-01-01
    • 2012-06-17
    • 2011-10-29
    相关资源
    最近更新 更多