write an array of 8 bit binary to text file?

Hello again,
second question from me today, albeit not quite as complex as the previous.
I have created an array of 8 bit binary groups in the format: '195 x 8 char array'
My intention is to output these to a file, so a second remote user can import them in the same format. Currently, using the formatting operators, I am unable to do so. The closest I have come to achieving my goal is a single concananated string.
I want to write the 8 bit binary groups to a file called 'ENCODE OUTPUT', the binary groups are arranged vertically as follows:
'00101111'
'00101111'
'01110010'
and so on...
My code is as follows:
fid =fopen('ENCODE OUTPUT.txt', 'wt' );
fprintf(fid, '%s,8\n', binX);
fclose(fid);
binX is the variable that contains the entire binary data.
Please accept my apologies if my terminology is off, and thank you for any assistance you can offer.

 Accepted Answer

You don't need fopen, fprintf, or fclose. A simple script like this will do the trick:
binX = ['00101111'; '00101111'; '01110010'];
writematrix(binX, 'yourfile.txt');

4 Comments

Hi Scott, thanks for the suggestion.
As my file contains 195 rows of 8 bit binary groups, would I have to manually enter each of the binary codes to use what you have provided?
I stumbled upon another method that seems to be working but I am open to learning and changing if there is a better way to overcome my problem?
what seems to be working is:
fid =fopen('ENCODE OUTPUT.txt', 'wt' );
fprintf(fid, '%s', [ binX.'; repmat(char(13), 1, size(binX,1)) ] );
fclose(fid);
This uses an ASCII carriage return at the end of each column from what I can see.
Your question implies you have 195 binary char arrays in variable named binX and you want to write them to a file. My answer is a simply way to do that.
You are also interested in reading those values back into MATLAB from the file. Again, no need to use fopen and fclose. You can use readmatrix. However, there is a some extra work to do if you want the data as binary characters in a char array, rather than as numbers. Here's how to do that:
% original data
binX = ['00101111'; '00101111'; '01110010'];
% write to file
filename = 'yourfile.txt'; % change as desired
writematrix(binX, filename);
% read from file (into a char array)
opts = detectImportOptions(filename);
opts.VariableTypes = 'char';
binX2 = readmatrix(filename, opts);
binX2 = char(binX2)
Output:
binX2 =
3×8 char array
'00101111'
'00101111'
'01110010'
That is a super helpful and detailed reply Scott. Thank you so much for taking the time to help here.
You're welcome. Glad to help. Good luck.

Sign in to comment.

More Answers (0)

Products

Release

R2021a

Community Treasure Hunt

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

Start Hunting!