0

does anyone know how to save an uint8 workspace variable to a txt file? I tried using MATLAB save command:

save zipped.txt zipped -ascii

However, the command window displayed warning error:

Warning: Attempt to write an unsupported data type to an ASCII file.
Variable 'zipped' not written to file.

3 Answers 3

1

In order to write it, simply cast your values to double before writing it.

A=uint8([1 2 3])

toWrite=double(A)

save('test.txt','toWrite','-ASCII')

The reason uint8 can't be written is hidden in the format section of the save doc online, took myself a bit to find it.

The doc page is here: http://www.mathworks.com/help/matlab/ref/save.html

The 3rd line after the table in the format section (about halfway down the page) says:

Each variable must be a two-dimensional double or character array.

Alternatively, dlmwrite can write matrices of type uint8, as the other poster also mentioned, and I am sure the csv one will work too, but I haven't tested it myself.

Hopefully that will help you out, kinda annoying though! I think uint8 is used almost exclusively for images in MATLAB, but I am assuming writing the values as an image is not feasible in your situation.

Sign up to request clarification or add additional context in comments.

Comments

0

have you considered other write-to-file options in Matlab?

How about dlmwrite?
Another option might be cvswrite.

For more information see this document.

Comments

0

Try the following:

%# a random matrix of type uint8
x = randi(255, [100,3], 'uint8');

%# build format string
frmt = repmat('%u,',1,size(x,2));
frmt = [frmt(1:end-1) '\n'];

%# write matrix to file in one go
f = fopen('out.txt','wt');
fprintf(f, frmt, x');
fclose(f);

The resulting file will be something like:

16,108,149
174,25,138
11,153,222
19,121,68
...

where each line corresponds to a matrix row.

Note that this is much faster than using dlmwrite which writes one row at a time

2 Comments

I rolled back the suggested edit because it was incorrect. The x' was used to transpose the matrix x, and was not intended as a quoted string: mathworks.com/help/matlab/ref/ctranspose.html
The reason for the transpose is that matrices in MATLAB are traversed in a column-major order, but we wanted to write it to file row by row instead. In this case I was a bit lazy and should have used the non-conjugate transpose instead: x.' (here it doesn't really matter since the numbers are purely real)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.