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

1 visualización (últimos 30 días)
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

Respuesta aceptada

Amit
Amit el 31 de Dic. de 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 comentarios
Tadgh
Tadgh el 31 de Dic. de 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 el 31 de Dic. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by