In Matlab, one can evaluate an arbitrary string as code using the eval
function. E.g.
s = '{1, 2, ''hello''}' % char
c = eval(s) % cell
Is there any way to do the inverse operation; getting the literal string representation of an arbitrary variable? That is, recover s
from c
?
Something like
s = repr(c)
Such a repr
function is built into Python, but I've not come across anything like it in Matlab, nor do I see a clear way of how to implement it myself.
The closest thing I know of is something like disp(c)
which prints out a representation of c
, but in a "readable" format as opposed to a literal code format.
The closest there is in Matlab is mat2str
, which works for numeric, character or logical 2D arrays (including vectors). (It doesn't work for ND arrays, cell arrays, struct arrays, or tables).
Examples:
>> a = [1 2; 3 4]; ar = mat2str(a), isequal(eval(ar), a)
ar =
'[1 2;3 4]'
ans =
logical
1
>> a = ['abc'; 'def']; ar = mat2str(a), isequal(eval(ar), a)
ar =
'['abc';'def']'
ans =
logical
1
In this related question and answers you can see:
OK, I see your pain.
My advice would still be to provide a function of the sort of toString
leveraging on fprintf
, sprint
, and friends, but I understand that it may be tedious if you do not know the type of the data and also requires several subcases.
For a quick fix you can use evalc
with the disp
function you mentioned.
Something like this should work:
function out = repr(x)
out = evalc('disp(x)');
end
Or succinctly
repr = @(x) evalc('disp(x)');
Depending on exactly why you want to do this, your use case may be resolved with matlab.io.saveVariablesToScript
Here is the doc for it.
Hope that helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With