jliu1729
jliu1729

Reputation: 13

MATLAB uint8 data type variable save

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.

Upvotes: 0

Views: 2152

Answers (3)

Amro
Amro

Reputation: 124563

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

Upvotes: 0

Shaun314
Shaun314

Reputation: 3461

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.

Upvotes: 1

Shai
Shai

Reputation: 114816

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

How about dlmwrite?
Another option might be cvswrite.

For more information see this document.

Upvotes: 0

Related Questions