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