Matlab Conversion Function

In Matlab, you can evaluate an arbitrary string as code using a function eval. For example.

s = '{1, 2, ''hello''}'  % char
c = eval(s)              % cell

Is there a way to do the reverse operation; getting a string representation of an arbitrary variable? That is, recover sfrom c? Sort of

s = repr(c)

Such a function repris built into Python, but I have not seen anything like it in Matlab and I do not see a clear way to implement it.

The closest thing that I know of is similar to disp(c)that which prints the presentation c, but in a “readable” format, not in a literal format.

+6
source share
3 answers

, , matlab.io.saveVariablesToScript

.

, !

+2

Matlab mat2str, , 2D- ( ). ( ND, , ).

:

>> 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

:

  • , , , char .
  • , Octave .
+6

, .

My advice would still be to provide a function such as toStringuse fprintf, sprintand friends, but I understand that it can be tedious if you don't know the data type and also requires a few sub-cases.

For a quick fix, you can use evalcwith the function you specified disp.

Something like this should work:

function out = repr(x)
    out = evalc('disp(x)'); 
end

Or succinctly

repr = @(x) evalc('disp(x)');
+3
source

All Articles