Writing array data to file

조회 수: 3 (최근 30일)
Peter Bu
Peter Bu 2018년 9월 27일
댓글: Peter Bu 2018년 9월 27일
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
Peter Bu
Peter Bu 2018년 9월 27일
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 2018년 9월 27일
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.

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
Stephen23 2018년 9월 27일
편집: Stephen23 2018년 9월 27일
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
Peter Bu
Peter Bu 2018년 9월 27일
Thanks alot! You really helped me! ;-)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Low-Level File I/O에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by