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

1 Ansicht (letzte 30 Tage)
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

Akzeptierte Antwort

Amit
Amit am 31 Dez. 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 Kommentare
Tadgh
Tadgh am 31 Dez. 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 am 31 Dez. 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by