Generating a for loop and writing data

3 views (last 30 days)
Robert
Robert on 8 Dec 2014
Commented: Shoaibur Rahman on 8 Dec 2014
I have a lot of data and need to do many stepwise regressions. The data is set out in 3 columns and 12040 rows. Each regression should include only 8 rows of data e.g. regression 1 1:8, regression 2 9:16 etc
So far the important part of my code looks like this (this gives me the correct output for the first regression)
xx=data(1:8,2:3); yy=data(1:8,1); [B,SE,PVAL,INMODEL,STATS,NEXTSTEP,HISTORY]=stepwisefit(xx,yy,'penter',.05);
I need to put this in a loop so that it will cycle through as specified above, what should this loop look like?
As this will spit out a lot of data, is there a way for the Coefficients and P values to be written to a file each time?
Any help is greatly appreciated as I'm relatively new to matlab :)

Answers (2)

Shoaibur Rahman
Shoaibur Rahman on 8 Dec 2014
Edited: Shoaibur Rahman on 8 Dec 2014
for i = 1:size(data,1)/8
xx=data(8*i-7:8*i,2:3); yy=data(8*i-7:8*i,1);
% append other stuffs here, use loop index to save B, SE, PVAL etc. values.
end
Mare sure that the data length (number of rows) is multiple of 8. If not, you can use ceil, floor, round, etc. functions, or append some rows of zeros at the end each column as per your requirement. I hope this should help.
  2 Comments
Henrik
Henrik on 8 Dec 2014
Damn, you beat me to it!
One comment, though, it's not always a good idea to use i as index, since MATLAB also uses it for the imaginary unit.
Shoaibur Rahman
Shoaibur Rahman on 8 Dec 2014
Hi Henrik,
Thanks for that note. Just to share, this is true both for i and j. So, it is better not to use those as vector or matrix indices. However, if I am certain that I am not handing complex numbers in any part of the code, then it is okay. Yet, good practice is to avoid those. Thanks.

Sign in to comment.


Henrik
Henrik on 8 Dec 2014
Edited: Henrik on 8 Dec 2014
This could be a start. I don't know exactly what output stepwisefit gives, and which parts of it you want to save, but I've given some examples of how to store B that hopefully will lead you the right way.
sz=size(data);
for k=1:sz(1)/8
xx=data((k-1)*8+(1:8),2:3);
yy=data((k-1)*8+(1:8),1);
[B,SE,PVAL,INMODEL,STATS,NEXTSTEP,HISTORY]=stepwisefit(xx,yy,'penter',.05);
%examples of how to save B, depending on what you want
%[B(k),SE,PVAL,INMODEL,STATS,NEXTSTEP,HISTORY]=stepwisefit(xx,yy,'penter',.05);
%[B(k,:),SE,PVAL,INMODEL,STATS,NEXTSTEP,HISTORY]=stepwisefit(xx,yy,'penter',.05);
%[B{k},SE,PVAL,INMODEL,STATS,NEXTSTEP,HISTORY]=stepwisefit(xx,yy,'penter',.05);
end

Community Treasure Hunt

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

Start Hunting!