Please help: Output as 'text' file in 'for' loop not moving to new line - not the standard '\r\n' fix

1 次查看(过去 30 天)
Please Please help..
Hi i have tried everything in my knowledge to fix this problem. I am working within 2 for loops to calculate TotalRadiation as a scaler 8760 time. As seen below i then created a matrix that shows the day, time and TotalRadiation. When I open the file, i only get the last result so therefore it is not moving to a new line with every iteration..
A=vec2mat(TotalRadiation,1);
B=[n,LST,A]
fileID = fopen('solardata.txt','w');
fprintf(fileID,'%3s %2s %12s\r\n','Day','Hour','Total Radiation [(W/m)^2]');
fprintf(fileID,'%3f %2.2f %12.8f\r\n',B);
fclose(fileID);
Thank you in advance
Tadgh

采纳的回答

Amit
Amit 2013-12-31
I don't see the loop. If the loop is applied on the code you gave here, it will produce only the last line. In every loop, you are opening the file 'solardata.txt' with 'w' option which means it will discard previous info and write the new information. I think if you do something like
fileID = fopen('solardata.txt','a')
This will work.
  2 个评论
Tadgh
Tadgh 2013-12-31
Thank you so much, something so simple has caused me 2 days of pain. I am now getting an output as seen below
Day Hour Total Radiation [(W/m)^2]
243.000000 4.00 1060.72143160
Day Hour Total Radiation [(W/m)^2]
0.000000 0.00 0.00000000
Day Hour Total Radiation [(W/m)^2]
0.000000 1.00 0.00000000
As seen the header is showing before every line of data. How would I get rid of this so as it only prints once?
Thank you
Amit
Amit 2013-12-31
I would open the file before getting in the loop and also add the header before getting in the loop. This will solve the issue.
Moreover, Opening a file over and over is very inefficient especially if it is done ~9000 times.
Another way is to write the information once at the end. You can store all the pieces of information in a matrix (in you case n*3). This will be a lot quicker than your current approach.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by