For loop to write in Excel file

Hi I have a problem with for loop and xlswrite statements. Actually I want to have a nested loop like this:
fid = fopen ('data1.xlsx', 'r');
fid = fopen ('reg1.txt', 'w');
for i = 1:4
x = data1(:,i);
for j = 2:5
y = data1(:,j);
p = polyfit(x,y,1);
yfit = polyval(p,x);
yresid = y - yfit;
ssresid = sum(yresid.^2);
A = ([i; j; ssresid]);
reg1 = xlswrite('reg.xlsx', [i, j, ssresid]);
end
end
and write the results of all iterations in Excel. However, I don't know how I can do this. The above code can just write the last iteration on the Excel file that it doesn't work for me. I want to have all iterations.
It would be great, If you can help me.
Thanks in advance

 Accepted Answer

This one should work:
fid = fopen ('data1.xlsx', 'r');
fid = fopen ('reg1.txt', 'w');
A = [];
for i = 1:4
x = data1(:,i);
for j = 2:5
y = data1(:,j);
p = polyfit(x,y,1);
yfit = polyval(p,x);
yresid = y - yfit;
ssresid = sum(yresid.^2);
A(:,end+1) = ([i; j; ssresid]);
end
end
reg1 = xlswrite('reg.xlsx', A);

More Answers (0)

Categories

Find more on Environment and Settings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!