【问题标题】:automatically insert nans without overwriting自动插入nans而不覆盖
【发布时间】:2020-01-19 12:43:06
【问题描述】:

我有一个代码可以告诉我在哪些位置缺少数据。我需要将 NaN 放在那里,使 MagMatrix1 更长。在下面的代码中,缺少 4 个数据,因此需要将 4 个 Nan 列添加到矩阵中。

vind=[5, 7, 10, 13];

MagMatrix=[ 99 98 97 94 95 96 93 92 91 96 95 94 98 98 ]
MagMatrixH1=[MagMatrix1(:,1:vind(1)-1),nanny,MagMatrix1(:,vind(1):vind(2)-2),nanny,MagMatrix1(:,vind(2)-1:vind(3)-3),nanny,MagMatrix1(:,vind(3)-2:vind(4)-4),nanny,MagMatrix1(:,vind(4)-3:end)];

这是基于这里解释的原理:https://nl.mathworks.com/matlabcentral/answers/1085-inserting-a-column-in-a-matrix-without-deleting-any-column 作为输出给予

MagMatrixH1=[ 99 98 97 94 NaN 95 NaN 96 93 NaN 92 91 NaN 96 95 94 98 98 ]

使 NaN 位于位置 5、7、10、13

这可行,但如果vind 的长度不同并且我需要添加例如 10 个 NaN 行,我该怎么办?我如何自动化这一点,我不需要每次都手动重写 MagMatrixH1 的代码?基本上,我想要做的是将 NaN 添加到矩阵中而不覆盖已经存在的内容。

【问题讨论】:

    标签: matlab matrix nan overwrite


    【解决方案1】:

    一种选择是制作一个包含所需大小的NaN 值的矩阵,然后将非NaN 值分配给它。您可以使用setdiff 来获取非NaN 值的索引:

    N = numel(MagMatrix)+numel(vind);
    MagMatrixH1 = nan([1 N]);
    MagMatrixH1(setdiff(1:N, vind)) = MagMatrix;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-07
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      相关资源
      最近更新 更多