New Line in text file from Matlab
5 views (last 30 days)
Show older comments
Abhikaran Amitkumar Bhatia
on 4 Mar 2022
Commented: Abhikaran Amitkumar Bhatia
on 9 Mar 2022
I want create multiple line and columns in text file from matlab to read measurement test data.
So far, I am able to do basic stuff. But any tips how can I proceed the above the task. Also the column should only contain 8 character. So there should be 10 column each column has 8 character in it. Character can be integer, strings
0 Comments
Accepted Answer
Voss
on 4 Mar 2022
% random numbers for data to write to text file:
data = randn(20,10)*1e6;
% open the file for writing:
fid = fopen('test_output.txt','w');
% write each value as an 8-character-wide floating-point number, followed by
% a space; after every 10 such columns of values, write a newline (\n):
fprintf(fid,[repmat('%8f ',1,10) '\n'],data.');
% close the file:
fclose(fid);
% check that the resulting text file contains the same matrix as 'data',
% within the floating-point precision used:
data_from_file = readmatrix('test_output.txt');
difference = abs(data_from_file-data);
max(difference(:))
8 Comments
Voss
on 8 Mar 2022
Edited: Voss
on 8 Mar 2022
mod is different from rem for negative arguments - not a factor here.
mod(x,8) == 0 means x is a multiple of 8, not a multiple of 2. mod(x,2) == 0 would mean x is a multiple of 2.
Since the code is resetting count to 0 in that case, I could've just as easily done if count == 8 rather than if mod(count,8) == 0
fprintf(fid,'+\n+'); prints a + then starts a new line and then prints another + at the beginning of the new line. (Then fprintf(fid,'%7s',' '); prints seven spaces immediately after that first + of the line.)
So you've basically understood the loop already: it is printing each number, and when it has printed 8 numbers, end the line with a + and start the next line with a + and seven spaces, then continue printing numbers.
More Answers (0)
See Also
Categories
Find more on Language Support in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!