Error on write to text file
6 views (last 30 days)
Show older comments
Hi everyone
I want to output the simulink results to a text file during running simulation. But the values of the text file are different with the true values (compare with the values in the Workspace). I also use Bock to export the result to a mat file and compare the result with the text file: The values in the mat file are the same as the values in the Workspace. I also know that this is the true values. But the values in the text file are different. For example the value in the workspace and mat file is 0.9913, but in text file is 1.012. But infact, the true values do not exceed 1. While the simulation, the values in the text file are always bigger than actual values. Please help me.
4 Comments
Answers (3)
Fangjun Jiang
on 26 Sep 2011
I just confirmed that with fopen(File,'w'), the content of the file will be over-written. So you will only get the last value, which is not intended.
There might be a way to not to run fopen() and fclose() at every time step. Bu the easiest way is to write the text file in appending mode. Use fopen(File,'at').
16 Comments
Walter Roberson
on 28 Sep 2011
You believe that u is one value at any time point, but did you use disp() or put in a break-point to cross-check that ?
Fangjun Jiang
on 30 Sep 2011
@Tung, any update? Another suggestion is to set the sample time to be 0.01 instead of inherit. I think that will help to get to the bottom of this problem.
Jan
on 27 Sep 2011
Your code does not insert spaces after writing a number: "sys=fprintf(fid,'%f',u)". But your data contain spaces: "0.000000 0.000000 0.001569 ...". Either you did not post the original code or your run another program.
Please set a breakpoint in the FPRINTF line to find out, what's going on.
Jan
on 26 Sep 2011
How do you create the text file? It seems to be obvious that there is a bug in this routine.
[EDITED] after reading your comment showing the code:
FPRINTF works correctly. So either you do not wnat u but x, or you write to a file in the current folder, but this is not the folder you are expecting. Then the file with the "wrong" values was written by an earlier version.
Better add the path to the output file and check the success of FOPEN in every case:
fid = fopen(fullfile(tempdir, 'value.txt'), 'w');
if fid < 0, error('Cannot open file'); end
2 Comments
Fangjun Jiang
on 26 Sep 2011
Also, try fopen(fullfile(tempdir, 'value.txt'), 'at'), which means writing text file and appending it. I am not sure if 'w' alone will overwrite the previous file.
See Also
Categories
Find more on String 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!