Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple Matlab utility to test and return the relative precedence of the given arguments. Inspired by Matt J's answer to the Matlab Answers question "How can I determine if one class is superior or inferior to another?" (http://www.mathworks.com/matlabcentral/answers/89208)
function [priority,classes] = argPrecedence(varargin)
% argPrecedence Return the relative class priority of the arguments
%
% Returns an array the same size as the argument list with each argument's
% relative priority level, with 1 as the highest.
%
% Optionally returns a second output of class names, with the unique classes
% of the argument list arranged in priority order.
%
% Note that the priority is dependent both on argument position and class.
priority = nan(size(varargin));
classes = cellfun(@class,varargin,'un',false);
args = varargin;
arg_idxs = 1:numel(args);
arg_classes = classes;
p = 1;
while ~isempty(args)
try
undefined_function_____(args{:})
catch ME
assert(strcmp(ME.identifier,'MATLAB:UndefinedFunction'))
C = textscan(ME.message,'%s','delimiter','''');
superior_class = C{1}{4}; % Dependent on locale, probably.
mask = strcmp(arg_classes,superior_class);
assert(any(mask),'The error message does not have a class of an argument')
priority(arg_idxs(mask)) = p;
p = p + 1;
args(mask) = [];
arg_idxs(mask) = [];
arg_classes(mask) = [];
continue
end
error('function should always error')
end
assert(~any(isnan(priority)),'Some arguments were not assigned a priority.')
if nargout > 1
% Return class names in priority order
[~,idxs] = sort(priority);
classes = unique(classes(idxs),'stable');
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment