I want to ignore nan values and substract others.

보은 이 on 13 Sep 2022
Latest activity Reply by Christopher Stapels on 19 Sep 2022

I have a data.
And, I want to substract the data using for.
But, I want to ignore the nan values and substract others.
For example, [1, 2, 3, NaN, 6, 9, 12, 14] ---- substract---> [1, 1, 3, 3, 2]
How can I do this?
Christopher Stapels
Christopher Stapels on 13 Sep 2022
What is the expected answer? I'm not clear what you mean by subtract for arrays.
[1,2,3,6,9,12,14] - [ 1,1,3,3,2] =?
Here is how you can clean the nan values though:
A=[1, 2, 3, NaN, 6, 9, 12, 14];
AnoNan=A(~isnan(A));
B = [1, 1, 3, 3, 2];
BnoNan=B(~isnan(B));
보은 이
보은 이 on 14 Sep 2022 (Edited on 14 Sep 2022)
Thanks for your answer!
I want to this.
A=[1, 2, 3, NaN, 6, 9, 12, 14]; ---> B = [A(2)-A(1), A(3)-A(2), A(4)-A(3). A(5)-A(4) ....]
But, There is a data including the NaN values in my loop.
I want to get the rate of change of sensor data.
load('data_20220716.mat'); % SOG[m/s] / COG[rad] / time[sec]
data = data2{5, 1};
SOG_time_data = [data(:, 1) data(:, 3)];
COG_time_data = [data(:, 2) data(:, 3)];
threshold_SOG = 0.1;
threshold_COG = 0.1;
for i = 2 : 1 : length(data)
if isnan(SOG_time_data(i-1, 1)) || isnan(SOG_time_data(i-1, 2))
SOG_time_data(i-1, :) = nan;
elseif isnan(SOG_time_data(length(data), 1)) || isnan(SOG_time_data(length(data), 2))
SOG_time_data(length(data), :) = nan;
end
if isnan(COG_time_data(i-1, 1)) || isnan(COG_time_data(i-1, 2))
COG_time_data(i-1, :) = nan;
elseif isnan(COG_time_data(length(data), 1)) || isnan(COG_time_data(length(data), 2))
COG_time_data(length(data), :) = nan;
end
% SOG_time_data_index = [find(isnan(SOG_time_data(:, 1)), 1, 'last'), 1];
% ddd_SOG_time_data(:, :) = SOG_time_data(~isnan(SOG_time_data(i, :))) - SOG_time_data(~isnan(SOG_time_data(i-1, :)));
if isnan(SOG_time_data(i-1, 1))
continue
else
d_SOG_time_data(i-1, :) = SOG_time_data(i, :) - SOG_time_data(i-1, :);
end
if isnan(COG_time_data(i-1, 1))
continue
else
d_COG_time_data(i-1, :) = COG_time_data(i, :) -COG_time_data(i-1, :);
end
end
Christopher Stapels
Christopher Stapels on 14 Sep 2022
The fucntion diff does that for you.
A=[1, 2, 3, NaN, 6, 9, 12, 14];
AnoNan=A(~isnan(A));
AnoNanDiff= diff(AnoNan);
보은 이
보은 이 on 15 Sep 2022
Thx Christopher Staples!
But, the index of data must not be changed
Christopher Stapels
Christopher Stapels on 19 Sep 2022
Are you replacing Nan with a value then? If you leave the index constant, you wont be able to do
A(4)-A(3)
for A=[1, 2, 3, NaN, 6, 9, 12, 14];