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

1 view (last 30 days)
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

Accepted Answer

Amit
Amit on 31 Dec 2013
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 Comments
Tadgh
Tadgh on 31 Dec 2013
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 on 31 Dec 2013
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Matrices and Arrays 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!