【问题标题】:Save Matrix values when values change from NaN to a Number in MATLAB当值从 NaN 更改为 MATLAB 中的数字时保存矩阵值
【发布时间】:2014-09-08 15:23:09
【问题描述】:

我有一个 3x15000 矩阵,我想在从 NaN 更改为数字期间保存这些段。所以我有很大的部分,所有 3 行都是 NaN,当它发生变化时,我想生成一个新矩阵。最好索引起点和终点吗?我如何设置一个标志以逐步遍历所有数据?

例如:

NaN 5.30669473796592 5.82479888441640 NaN NaN 103.308010031436 103.534581233064 NaN NaN 1787365.55338272 1745186.16219408 NaN

所以我想保存中间的数值。

【问题讨论】:

  • 你能提供一个你想要的输出的小例子吗?

标签: matlab matrix indexing


【解决方案1】:

如果我错了,请纠正我,但听起来您的 3x15000 矩阵包含一些离散数据,您希望将每个数据块保存为单独的矩阵。

假设您的矩阵如下所示:

h(:,[2,3,5]) = rand(3,3)

h =

   NaN    0.9649    0.9572       NaN    0.1419       NaN
   NaN    0.1576    0.4854       NaN    0.4218       NaN
   NaN    0.9706    0.8003       NaN    0.9157       NaN

现在您想将第 2,3 列复制到一个矩阵中,将第 5 列复制到另一个矩阵中。一种方法是首先找到仅包含 NaN 的列。你可以这样做:

ind = all(isnan(h),1)

ind =

 1     0     0     1     0     1

isnan 返回一个由 1 和 0 组成的数组,其中 1 表示 NaN 所在的位置。 all(...,1) 返回所有行都是 NaN 的列索引。 ind 包含您想要的标志。要单独保存每个数据块,您可以使用简单的for 循环。这是一个快速而肮脏的解决方案:

j = 1;
k = 1;
x = nan(3,1); %temporary matrix to store numerical values
c = cell(2,1); %cell array to store the chunks of data individually
               %if you can predict how many elements `c` should have, then
               %you can pre-allocate appropriately.

for i=1:length(ind)    
    %loop through all the columns

    if ind(i) == 1  
        %if we encounter a flag and 'x' has data, dump 'x' into 'c{k}',
        %reset 'x' and continue.

        if ~all(isnan(x))
            c{k} = x; 
            k = k+1;
        end

        %reset x
        x = nan(3,1);
        j=1;
        continue
    end


    x(:,j) = h(:,i);
    j = j+1;

    %catch data at the end, if last column of h does not contain all NaNs
    if i==length(ind)
        c{k} = x;
    end

end

您的数据块以矩阵形式存储在元胞数组中:

c{1}

ans =

    0.9649    0.9572
    0.1576    0.4854
    0.9706    0.8003

c{2}

ans =

    0.1419
    0.4218
    0.9157

希望这会有所帮助。

【讨论】:

  • 这就是我一直在寻找的东西。非常感谢!
【解决方案2】:

我不确定你想要什么样的输出,但这里有一种方法可以去掉 NaN 元素:

让我们考虑这个矩阵:

A =

   NaN     1     2   NaN     3     4   NaN
   NaN     5     6   NaN     7     8   NaN
   NaN     9    10   NaN    11    12   NaN

然后使用find 命令,我们可以获得所有元素都是NaN 的列(如您在问题中所述):

[~ ,col] = find(isnan(A))

col =

     1
     1
     1
     4
     4
     4
     7
     7
     7

然后我们可以从A中删除它们,形成一个新的矩阵:

A(:,col) = []

A =

     1     2     3     4
     5     6     7     8
     9    10    11    12

这是你的想法吗?如果不是,请更具体。谢谢!

【讨论】:

    猜你喜欢
    • 2015-04-20
    • 1970-01-01
    • 1970-01-01
    • 2018-03-06
    • 2018-11-26
    • 2012-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多