I\'m looking for a function in Matlab to use for error messages, like so:
error([\'Invalid value for someVariable: \' wantedFunction(someVariable)]);
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]
Looks weird, but
str = matlab.unittest.diagnostics.ConstraintDiagnostic.getDisplayableString(value)
does the job for you instead using that unesthetic evalc(disp())
approach.
Come to think of it, I remember doing something a long time ago quite similar to what angainor has done in his answer. I'll post it here for anyone interested in converting arbitrary things to string, and generally having more control over how that conversion is done.
It supports empties, logicals, chars, function handles, numerics, cells, struct (arrays), and user-defined classes (sparse arrays in the next update).
EDIT: I've taken this as a template for an update that I ended up placing on the file exchange. Feel free to experiment it and modify to suit your needs.
No, there is no such function. I ran into similar problems, so here is a very rudimentary function that I use. Do realize that it is not complete. For example, it does not output fields of a structure in a meaningful way, but that can easily be added. You can treat it as a base implementation and fit it to your needs.
function ret = all2str(param)
if isempty(param)
if iscell(param)
ret = '(empty cell)';
elseif isstruct(param);
ret = '(empty struct)';
else
ret = '(empty)';
end
return;
end
if ischar(param)
ret = param;
return;
end
if isnumeric(param)
ret = num2str(param);
return;
end
if iscell(param)
ret = all2str(param{1});
for i=2:numel(param)
ret = [ret ', ' all2str(param{i})];
end
return;
end
if isstruct(param)
ret = '(structure)';
return;
end
end