Writing array data to file

9 views (last 30 days)
Peter Bu
Peter Bu on 27 Sep 2018
Commented: Peter Bu on 27 Sep 2018
Hello everyone,
I want to write this data to a file, but the data in matlab does not match with the data in the file. Whats the problem? Thanks in advance.
for z=1:columns
tension = tension_array{1,z};
epsilon = epsilon_array{1,z};
fileIDs = fopen(strcat(file_names{z,1},'_edited_strain.TXT'),'w','n','UTF-8');
fprintf(fileIDs,'%6s %12s\n','tension','strain');
fprintf(fileIDs,'%f64 %f64\n',tension,epsilon);
fclose(fileIDs);
end
  4 Comments
Peter Bu
Peter Bu on 27 Sep 2018
Yes they have to be in columns. And they each have the same length for every single file which is written.
Peter Bu
Peter Bu on 27 Sep 2018
The problem is that when I have the two arrays and I write them to the file, the data is not the same. Both Columns have pretty much the same value in the file, but when I look up the values in the workspace I see the correct values.

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 27 Sep 2018
Edited: Stephen23 on 27 Sep 2018
If tension and epsilon are non-scalar and are intended to be printed as columns then your code will not work. Text files are written by row (well, they are just written as a long vector of characters, with newlines interspersed), and all languages that have fprintf print to the file by row. It is not trivially possible to print one column, and then next column, and then a next column, etc. It is trivially possible to print one row, then the next row, etc., simply by appending to the end of that long character vector and adding newlines. This is not a limitation of MATLAB, it is simply due to how text files are stored.
Note that the fprintf help states that it "applies the formatSpec to all elements of arrays A1,... An in column order, and writes the data to a text file". So the solution is to put all of your data into one matrix, transpose it (so that the data is in column order), and then supply it to fprintf like this:
M = [tension_array{1,z}(:),epsilon_array{1,z}(:)]; % two columns
fprintf(fileIDs,'%g %g\n', M.'); % note the transpose.
It is not clear what you want %f64 to do: I could not find any reference to anything like this in the fprintf help (unless you really do mean the %f format specifier followed by the literal characters 64). You need to use a format specifier that is supported by MATLAB.
  1 Comment
Peter Bu
Peter Bu on 27 Sep 2018
Thanks alot! You really helped me! ;-)

Sign in to comment.

More Answers (0)

Categories

Find more on Debugging and Analysis 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!