Splitting Table at NaN

8 次查看(过去 30 天)
Umair Shahid
Umair Shahid 2022-4-14
编辑: Vatsal 2023-9-29
I have 2 tables and I want to split them at NaN values, for now I am ignoring repeated NaNs but I want to consider them in the next step. What I have now :
x = table2array(t(:,1));
y= table2array(t(:,2));
index=find(~isnan(x));
idx=find(diff(index)~=1);
A=[idx(1);diff(idx);numel(index)-idx(end)];
x_points=mat2cell(x(~isnan(x)),A,1);
y_points=mat2cell(y(~isnan(y)),A,1);
If two NaNs occur at once, I want it to become a NaN cell.

回答(1 个)

Vatsal
Vatsal 2023-9-22
编辑:Vatsal 2023-9-29
I understand that you are splitting the array “x” and ‘y” at the values of NaN. According to your code you are splitting “x” array at the values of NaN and wherever split happens in “x”, you are splitting “y” at the same location. Now you wanted to consider the repeated NaNs, which means if more than one consecutive NaNs are there you wanted to create a NaN cell also.
Below is the code which will consider repeating NaNs and provide the output as needed:
count = 0;
nanIndex = [];
nanIndices = find(isnan(x));
for i = 1:length(nanIndices)
if i > 1 && nanIndices(i) == nanIndices(i-1) + 1
count = count + 1;
else
count = 1;
end
if count > 2
nanIndex(end +1) = nanIndices(i);
end
end
x(nanIndex) = [];
disp(x);
nanIndices = find(isnan(x));
x_points = {};
y_points = {};
startIndex = 1;
for i = 1:length(nanIndices)
endIndex = nanIndices(i) - 1;
x_points{i} = x(startIndex:endIndex);
y_points{i} = y(startIndex:endIndex);
startIndex = nanIndices(i) + 1;
if i > 1 && nanIndices(i) - nanIndices(i-1) > 1
x_points{i-1} = NaN;
y_points{i-1} = NaN;
end
end
if startIndex <= length(x)
x_points{end+1} = x(startIndex:end);
y_points{end+1} = y(startIndex:end);
end
for i = 1:numel(x_points)
if all(isnan(x_points{i}))
x_points{i} = NaN;
y_points{i} = NaN;
end
end
I hope this helps!

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by