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일

0 개 추천

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!

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

제품

릴리스

R2022a

태그

질문:

2022년 4월 14일

편집:

2023년 9월 29일

Community Treasure Hunt

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

Start Hunting!

Translated by