File Exchange

image thumbnail

serialize

version 1.0 (5.02 KB) by

Create matlab code from a variable

4 Downloads

Updated

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
  eval(matcode)

Examples
  x = [1 2 3; 3 4 5];
  serialize(x)
  
  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 (9)

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';
  return
else
  val = 'struct(';
end
***

Sebastian

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

Matt Dunham

Matt Dunham (view profile)

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));
end

Matt Dunham

Matt Dunham (view profile)

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.

MATLAB Release
MATLAB 7.2 (R2006a)
Acknowledgements

Inspired: Serialize/Deserialize

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video