Subtract one column from another unless NaN

6 ビュー (過去 30 日間)
Carver Nabb
Carver Nabb 2019 年 1 月 8 日
回答済み: Totanly 2020 年 8 月 2 日
I have a 100x4 double (data) with various NaN values throughout.
345 123 546 864
183 152 NaN NaN
842 NaN 238 945
NaN 283 965 NaN
392 105 932 NaN...
...
I am trying to subtract the first time point (that's not a NaN) from the last time point (that's not a NaN).
Here is the code I am using. It not only does not work, but makes me think there has to be an easier/more efficient manner of solving this.
for i = 1:100
if isreal(data(i,4))
if isreal(data(i,1))
FirstMinusLast(i) = data(i,1) - data(i,4);
elseif isreal(data(i,2))
FirstMinusLast(i) = data(i,2) - data(i,4);
elseif isreal(data(i,3))
FirstMinusLast(i) = data(i,3) - data(i,4);
else
FirstMinusLast(i) = 'N/a';
end
elseif isreal(data(i,3))
if isreal(data(i,1))
FirstMinusLast(i) = data(i,1) - data(i,3);
elseif isreal(data(i,2))
FirstMinusLast(i) = data(i,2) - data(i,3);
else
FirstMinusLast(i) = 'N/a';
end
elseif isreal(data(i,2))
if isreal(data(i,1))
FirstMinusLast(i) = data(i,1) - data(i,2);
else
FirstMinusLast(i)= 'N/a';
end
end
end
  2 件のコメント
Totanly
Totanly 2019 年 1 月 8 日
You mean A(:,1)-A(:,4) excluding NaN?
Carver Nabb
Carver Nabb 2019 年 1 月 8 日
Yes, unless A(i,1) is NaN, then i would like to do A(i,2)-A(i,4). Assuming A(i,2) is real.

サインインしてコメントする。

回答 (3 件)

madhan ravi
madhan ravi 2019 年 1 月 8 日

Totanly
Totanly 2019 年 1 月 8 日
編集済み: madhan ravi 2019 年 1 月 8 日
c1=1 %or 2;
c2=3 %or 4
FirstMinusLast=data(:,c1)-data(:,c2); %if any NaN is there it will give NaN
data1=data(data>0);

Totanly
Totanly 2020 年 8 月 2 日
A=[345 123 546 864
183 152 NaN NaN
842 NaN 238 945
NaN 283 965 NaN
392 105 932 NaN]; %or make your own matrix
i=A>0;
A_new=A(i);
result=A_new(1)-A_new(length(A_new));

カテゴリ

Help Center および File ExchangeNaNs についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by