Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Matlab function to convert any data structure to a string?

Tags:

matlab

I'm looking for a function in Matlab to use for error messages, like so:

error(['Invalid value for someVariable: ' wantedFunction(someVariable)]);

I want wantedFunction to be able to take both strings, arrays, cell arrays, ideally even structure arrays.

For now, I'm using num2str, but that doesn't work for cells. I thought what I want could be done with sprintf, but I haven't figured out how. I suppose I could write my own function, but that would be redundant if there already is a way to do this in Matlab. Any ideas?

like image 666
Nagel Avatar asked Oct 09 '12 10:10

Nagel


1 Answers

Yes, although it's not straightforward. You have to use the disp in combination with evalc:

string = evalc(['disp(someVariable)'])

You could cast this into more manageable form:

toString = @(var) evalc(['disp(var)']);

So, for your example:

>> var = {rand(3,1), 'A', struct('test', 5)};
>> error(['Invalid value for var: ' toString(var)])

??? Invalid value for var:     [3x1 double]    'A'    [1x1 struct]
like image 76
Rody Oldenhuis Avatar answered Oct 30 '22 00:10

Rody Oldenhuis