MATLAB Answers

Values not getting printed in csv file

조회 수: 5(최근 30일)
Hi
I have a small issue in printing the values in .csv file
Code.
for
for
for
- some lines of code
fprintf("Temperature = %3.0f\n",temp);
[fid1, msg1] = fopen('file1.csv', 'w' );
fprintf(fid1, 'temperature');
fprintf(fid1, '%3.0f', temp );
fprintf(fid1, '\n');
fclose(fid1);
end
end
end
Output on the command line.
Temperature = -40
Temperature = 0
Temperature = 25
Temperature = 60
Temperature = -40
Temperature = 0
Temperature = 25
Temperature = 60
Temperature = -40
Temperature = 0
Temperature = 25
Temperature = 60
But in the CSV file i have only the last line of the output is printed.
Temperature = 60
I need to print all the values, what can be done ?

  댓글 수: 0

Sign in to comment.

채택된 답변

Stephen Cobeldick
Stephen Cobeldick 7 Jun 2020
편집: Stephen Cobeldick 7 Jun 2020
"Values not getting printed in csv file"
Actually they are getting printed, your code just keep overwriting them. The problem is that your code reopens the file on every loop iteration, and each time any existing file contents are simply discarded, so in the end, only the data from the last loop iteration will be in the file.
The usual solution is to open the file before the loops, and close it after the loops:
[fid, msg] = fopen('file1.csv','wt'); % this needs to be BEFORE the loops.
for
for
for
...
fprintf(fid, 'temperature %3.0f\n',temp);
end
end
end
fclose(fid); % this needs to be AFTER the loops
Alternatively you could open the file with the 'a' (append) option, but I would not recommend this as you would anyway need to fopen and fclose the file before the loop to clear any existing file data. The above solution is simpler.

  댓글 수: 9

표시 이전 댓글 수: 6
Ganesh Kini
Ganesh Kini 8 Jun 2020
How can i save the data in columns or in array? Probably in what way.
If you could give me an example. It would be great.
Stephen Cobeldick
Stephen Cobeldick 8 Jun 2020
[fid,msg] = fopen('file1.csv','wt');
assert(fid>=3,msg)
fprintf(fid,'%s\t%s\t%s\n','Temperature','Value_n','Value_p');
for
for
for
...
fprintf(fid,'%3.0f\t%1.1f\t%1.1f\n',temp,vnw,vpw);
end
end
end
fclose(fid);
Ganesh Kini
Ganesh Kini 9 Jun 2020
Hi,
It does not work as expected
Output
Temperature Value_n Value_p ,-40 0.2 0.1 20 0.1 0.4 120 0.5 4.5
where as i should get the output in such a way
Temperature, -40 20 120
Value_n, 0.2 0.1 0.5
Value_p, 0.1 0.4 4.5
Could you please suggest some changes ?

Sign in to comment.

추가 답변(0개)

태그


Translated by