I sometimes miss a function to produce a string representation of a (possibly nested) cell array. It would be a generalization of mat2str
, which only works for non-cell arrays (of numeric, char or logical type).
Given an array
x
, how to obtain a string representationy
, such that evaluating this string producesx
?
For example, the input
x = {[10 20], {'abc'; false; true;}};
should produce an output string like
y = '{[10 20], {''abc''; false; true}}';
(or some variation regarding spacing an separators), such that
isequal(x, eval(y))
is true
.
This process, transforming a data structure into a string that later can be evaled, is named serialization.
There is a serialize function for Octave that can be used for this purpose which supports any core data type (not only cell arrays) with any number of dimensions (not only 2d).
Examples:
## Works for normal 2d numeric arrays
octave> a = magic (4);
octave> serialize (a)
ans = double([16 2 3 13;5 11 10 8;9 7 6 12;4 14 15 1])
octave> assert (eval (serialize (a)), a)
## Works for normal 3d numeric arrays with all precision
octave> a = rand (3, 3, 3);
octave> serialize (a)
ans = cat(3,double([0.53837757395682650507 0.41720691649633284692 0.66860079620859769189;0.018390655109800025518 0.56538265981533797344 0.20709955358395887304;0.86811365238275806089 0.18398187533949311723 0.20280927116918162634]),double([0.40869259684132724919 0.96877003954154328191 0.32138458265911834522;0.37357584261201565168 0.69925333907961184643 0.10937000120952171389;0.3804633375950405294 0.32942660641033155722 0.79302478034566603604]),double([0.44879474273802461015 0.78659287316710135851 0.49078191654039543534;0.66470978375890155121 0.87740365914996953922 0.77817214018098579409;0.51361398808500036139 0.75508941052835898411 0.70283088935085502591]))
octave> assert (eval (serialize (a)), a)
## Works for 3 dimensional cell arrays of strings
octave> a = reshape ({'foo', 'bar' 'qux', 'lol', 'baz', 'hello', 'there', 'octave'}, [2 2 2])
a = {2x2x2 Cell Array}
octave> serialize (a)
ans = cat(3,{["foo"],["qux"];["bar"],["lol"]},{["baz"],["there"];["hello"],["octave"]})
octave> assert (eval (serialize (a)), a)
However, a better question is why do you want to do this in the first place? If the reason you're doing this is to send variables between multiple instances of Octave, consider using the parallel and mpi packages which have functions specialized designed for this purpose.