File Exchange

image thumbnail


version (1.98 KB) by Jøger Hansegård
Create matlab code from a variable

1 Download

Updated 29 Aug 2006

No License

matcode = SERIALIZE(x) generates matlab code of x
matcode = SERIALIZE(x, n) generates matlab code of x retaining n digits
of precision

SERIALIZE should be able to create matlab code of the following data types:
- matrices, vectors, and scalars of any class and dimension
- strings
- structs, arrays of structs with up to six dimensions
- cell arrays
- matlab objects with a copy constructor implemented
- empty values of any class
- any combinations hereof

The value of x can be obtained by

x = [1 2 3; 3 4 5];

x = uint8(rand(10)*5);
matcode = serialize(x)

x = {rand(3,3,3,4), 'a string value', {1 2 3; 1 3 3 }}
matcode = serialize(x, 30)

Comments and Ratings (10)

John Miller

This is brilliant. Thank you very, very much. I was faced with writing 100s of lines of code to save/load class variables. Your single file reduced it to 20 and makes it much more flexible with respect to adding new variables and maintaining backwards compatibility.

As Sebastian already said, empty structures need to be fixed.

I suggest you to substitute the code in line 134:
val = 'struct(';

with the following one:
if numel(fieldNames) == 0
val = 'struct';
val = 'struct(';


Empty structures are not handled correctly:
>> serialize(struct)
ans = 'struc);'

Matt Dunham

It would be nice if it also serialized function handles - the following changes would do the trick.

elseif isa(v, 'function_handle')
val = serializehandle(v);

function val = serializehandle(v)
val = sprintf('str2func(''%s'')', func2str(v));

Matt Dunham

This is fantastic - exactly what I was looking for. Thanks

Tom Muylle

It's too bad it doesn't work for matlab 6.5 :(

anony mouse

An absolutely wonderful piece of code. I wish I now had the ability to read the output into software like excel.

Steve Orzol

Nice. Thanks for the quick update. I can see using this with building xml strings.

Jøger Hansegård

This has been fixed by converting such strings to uint8. Thanks for noticing me.

Steve Orzol

x{1} = 'rick''s'

y = serialize(x)

z = eval(y) %gives ??? Error: Unexpected MATLAB expression.


Fixed bug when serializing strings with special characters

MATLAB Release Compatibility
Created with R2006a
Compatible with any release
Platform Compatibility
Windows macOS Linux

Inspired: Serialize/Deserialize