Outputing 256 characters into stream binary file

2 views (last 30 days)

Hello!

I am trying to export a txt file from Matlab that contains a 100000 x 11 array of values. Preceding these values, I want a header that has up to 256 characters, with "Unformatted Data Version: 202409251" being the first value. I am confused how to input this, and am worried that it is because of Matlab's 63 character limit. I am using "writematrix(data, 'data.txt')" to export to txt.
What I would like the output txt file to be is below:

Unformatted Data Version: 202409251 , Time= 3.81154488E-18
NrecordsFields 8640
1 3812 1 1 1 1 1.588E-03 -9.583E-06 -9.583E-06 0.000E+00 1
11 3822 1 1 1 1 1.592E-03 -9.583E-06 -9.583E-06 0.000E+00 1

Any help would be appreciated!!

Answers (1)

Suraj Kumar
Suraj Kumar on 26 Sep 2024
Hi Jaden,
From what I gather, you wanted to export a 100,000 * 11 array of values from MATLAB to a text file. To achieve this, you may refer to the following steps and the attached code snippets:
1. Prepare your data in a matrix format and construct the header in a string format.
% Define the header
header = [ ...
'Unformatted Data Version: 202409251 , Time= 3.81154488E-18\n' ...
'NrecordsFields 8640\n'];
2. Use the fopen function to open the file in write mode and write the header using the fprintf function.This function is used to write the header string to the file because it can handle long strings, thus circumventing any concerns about character limits.
% Open the file for writing
fileID = fopen('data.txt', 'w');
% Write the header
printf(fileID, header);
3. Close the file and then append the matrix data using writematrix function in write mode.
% Close the file
fclose(fileID);
% Append the data
writematrix(data, 'data.txt', 'Delimiter', ' ', 'WriteMode', 'append');
You may refer to the output below for a better understanding:
To know more about fprintf or writematrix functions in MATLAB, kindly refer to the following documentations:
Hope this helps!
  3 Comments
Jaden Hoechstetter
Jaden Hoechstetter on 27 Sep 2024
Thank you for your help.
Also, I want the the header to be strictly 256 character. An example in Fortran would be:
Character ABC*256
Thanks again.
Walter Roberson
Walter Roberson on 27 Sep 2024
Your request is ambiguous.
Do you need:
TEXT1<spaces_to_255><CR>TEXT2<spaces_to_255><CR>
or do you need
TEXT1<spaces_to_256><CR>TEXT2<spaces_to_256><CR>
or do you need
TEXT1<spaces_to_256>TEXT2<spaces_to_256>
or do you need
TEXT1<CR>TEXT2<CR><spaces_to_256>
or do you need
TEXT1<spaces_to_255><LF>TEXT2<spaces_to_255><LF>
and likewise other possibilities with LF instead of CR
Or do you need
TEXT1<spaces_to_254><CR><LF>TEXT2<spaces_to_254><CR><LF>
?

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!