Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab repr function

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.

like image 884
jmd_dk Avatar asked Oct 28 '17 20:10

jmd_dk


3 Answers

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:

  • A function I wrote for obtaining a string representation of 2D cell arrays with arbitrarily nested cell, numeric, char or logical arrays.
  • How to do what you want in Octave for arbitrary data types.
like image 112
Luis Mendo Avatar answered Oct 20 '22 01:10

Luis Mendo


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)');
like image 36
pacta_sunt_servanda Avatar answered Oct 20 '22 02:10

pacta_sunt_servanda


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!

like image 2
Andy Campbell Avatar answered Oct 20 '22 00:10

Andy Campbell