Often, my functions contain a string argument that has a small number of valid options. For example, it might represent a mode similar to the last argument of interp1
. When the user passes an incorrect value, I like to give a list of valid options in the error message.
Currently, I solve it like this:
function out = my_func(mode)
valid_modes = {'rectangular', 'gaussian'};
switch mode
case 'rectangular'
% do something
case 'gaussian'
% do something else
otherwise
error(['atmlab:' mfilename ':invalid'], 'Invalid mode: %s. Valid modes: %s', mode, sprintf('%s ', valid_modes))
end
The trick I'm exploiting is that sprintf
can take a cell array, and then outputs a concatenation of multiple strings. However, this behaviour appears to be undocumented, and as of Matlab 2012b, Matlabs Code Analyzer has started to warn against this usage of sprintf
. It still works, but it might not be a supported way and I don't know if it will remain working in the future, so I'm reluctant to simply ignore or suppress the warning.
Another solution would be to use evalc('disp(valid_modes)')
, but that solution makes me puke.
How do I conveniently and elegantly display the value of a cell array of strings?
Since recent versions of Matlab (I think since 2013b), there is a new function strjoin
, that joins strings in a cell array. For example:
C = {'Newton','Gauss','Euclid','Lagrange'};
str = strjoin(C,', ')