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