How do i omit NaN values from polyfit?

I am pulling data from an excel sheet that has empty cells in it which appear as NaNs. I am plotting the data in this excel file, and i want a best fit line to go through it. If i try to use the polyfit function, it returns NaN values because of the empty cells in the excel sheet. Is there anyway i can have the sheet omit the NaN values and only look at the cells with data in them?
filename = 'NB-Aroostook.xls';
numData = xlsread(filename);
[rows, columns] = size(numData);
x=(1:rows);
length= x.';
maxt=numData(1:rows,3);
figure(1)
hold on;
plot(length, maxt, 'LineWidth', .2);
pbaspect([3 1 1]);
fit1=polyfit(length,maxt,1);
plot(length,fit1,'Color','k');
xlabel('Year');
ylabel('Maximum Monthly Temperature (°C)');
Any help is appreciated!

 채택된 답변

Akira Agata
Akira Agata 2018년 3월 16일

5 개 추천

How about the following?
filename = 'NB-Aroostook.xls';
numData = xlsread(filename);
maxt = numData(:,3);
length = (1:size(numData,1))';
idx = any(isnan(maxt));
fit1 = polyfit(length(~idx),maxt(~idx),1);

댓글 수: 2

car
car 2018년 3월 16일
works like a charm! thanks!
+Small improvement:
Looking at my script again, I found any function in the 5th line is unnecessary. Please revise the line as follows.
idx = isnan(maxt);

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

질문:

car
2018년 3월 15일

댓글:

2018년 3월 18일

Community Treasure Hunt

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

Start Hunting!

Translated by