Matlab中的第一个非NaN元素值和索引 [英] first non NaN element value and index in matlab

查看:218
本文介绍了Matlab中的第一个非NaN元素值和索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从Matlab矩阵的每一列中获取第一个非NaN元素的值和索引.

在一个单独的问题中---没有NaN的列很少.因此,在这种情况下,我想从每列中提取第一个非NaN元素的值和索引,否则,如果列中不包含NaN,则提取每列的第一个元素.

有人可以针对这两个问题提供帮助吗?

解决方案

通过 sub2ind 从该索引中找到该值a>或手动计算相应的线性索引.

要在包含所有 NaN 的列中返回不同的索引,请使用 max 的第一个输出来检测这种情况并更改这些列的结果.

x 表示您的矩阵.然后:

  [m,index] = max(〜isnan(x),[],1);值= x(索引+(0:大小(x,2)-1)*大小(x,1));%//或等效x(sub2ind(size(x),index,1:size(x,2)))index(〜m)=大小(x,1);%//返回具有所有NaN的列的最后一个索引 

示例

  x = [8 NaN 3 NaNNaN 4 5 NaN]; 

产生

  index =1 2 1 2值=8 4 3 NaN 

I want to obtain value and index of first non-NaN element from each column of a matrix in the matlab.

In a separate problem--- There are few columns that does not have NaN. So in that case-- I would like to extract value and index of first non-NaN element from each column and otherwise first element of each column if column does not contain NaN.

Can anybody help regarding these two problems?

解决方案

The index is easily obtained with the second output of max. The value can be found from that index using sub2ind or computing the corresponding linear index manually.

To return a different index in columns that contain all NaN, use the first output of max to detect that situation and change the result for those columns.

Let x denote your matrix. Then:

[m, index]  = max(~isnan(x), [], 1);
value = x(index + (0:size(x,2)-1)*size(x,1));
        %// or equivalently x(sub2ind(size(x), index, 1:size(x,2)))
index(~m) = size(x, 1); %// return last index for columns that have all NaN

Example

x = [  8    NaN     3    NaN
      NaN     4     5    NaN];

produces

index =
     1     2     1     2
value =
     8     4     3   NaN

这篇关于Matlab中的第一个非NaN元素值和索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆