Search code examples
arraysmatlabcell

How to display error including content of cell array


I want to display each element of a cell array in new line as part of an error message in Matlab.

classdef MyEnum < int32
    enumeration
         red (1) 
         blue (2) 
    end
end    

[m, s] = enumeration('MyEnum');
error('Expected one of the values below: %s', s);

That code didn't work and returned following error: "Function is not defined for 'cell' inputs."

I want display an error message like this.

 Expected one of the values below:
 'red'
 'blue'

Solution

  • If the cells only contain character vectors

    You can expand the cell into a comma-separated list of individual inputs to error, and dynamically build the format specifier by repeating '%s\n' the appropriate number of times. This encloses each string in single quotes.

    s = {'aaa', 'bbbb'};
    error(['Expected one of the values below:\n' repmat('''%s''\n', 1, numel(s))], s{:})
    

    gives the error message

    Expected one of the values below:
    'aaa'
    'bbbb'
    

    If the cells can contain character vectors or numeric matrices

    In this case, instead of enclosing in single quotes you can apply mat2str to each cell's contents:

    s = {'aaa', [1 2 3; 4 5 6]};
    t = cellfun(@mat2str, s, 'UniformOutput', false);
    error(['Expected one of the values below:\n' repmat('%s\n', 1, numel(t))], t{:})
    

    gives

    Expected one of the values below:
    'aaa'
    [1 2 3;4 5 6]