Is it possible to use a for loop to change which linear regression to use for optimization purposes?
4 次查看(过去 30 天)
显示 更早的评论
I'm trying to optimize my code where I want to discover which linear regression model is optimal to use, looking at R^2. So far this is what I've come up with (where M1 and M2 are parts of two tables):
[linear1, gof]=fit(M1,M2,'poly1');
linear1_R2=gof.rsquare
%
[linear2, gof]=fit(M1,M2,'poly2');
linear2_R2=gof.rsquare
%
[linear3, gof]=fit(M1,M2,'poly3');
linear3_R2=gof.rsquare
...
I want to do this until poly9 and it feels like it can be optimized. I was thinking about doing a for loop where the program (1) will run all the fit functions and (2) display which one gives the highest R^2 and what that value is, but I'm not sure how to proceed.
Hope someone can help, thanks in advance!
0 个评论
采纳的回答
Rishabh Gupta
2018-7-27
编辑:Rishabh Gupta
2018-7-27
Hi Anna,
The below code snippet can accomplish the task. It fits all the models specified it 'fit_func' array and records the R^2 value in a vector. Finally, the model with the highest R^2 value can be easily extracted.
fit_func={'poly1','poly2','poly3','poly4','poly5','poly6','poly7','poly8','poly9'};
rsquare_values=zeros(length(fit_func),1);
for i=1:length(fit_func)
[linear1, gof]=fit(M1,M2,fit_func{i});
rsquare_values(i)=gof.rsquare;
end
[best_rsquare,index] = max(rsquare_values);
best_model = fit_func(index);
best_rsquare - highest R^2 value corresponding to the best model.
best_model - contains the model with the highest R^2 value.
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Linear and Nonlinear Regression 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!