Borrar filtros
Borrar filtros

assignin 'caller' fails when variable is a matlab function in the path

7 visualizaciones (últimos 30 días)
Maximilien Chaumon
Maximilien Chaumon el 5 de Mzo. de 2014
Editada: Matt J el 7 de Mzo. de 2014
I wrote this handy function to parse 'key', value pairs in function calls with using varargin. The function goes as follows:
function setdefvarargin(in,varargin)
% assign default 'param' value pairs in the calling workspace
%
% input param value pairs are assigned to variables in the calling
% workspace. default values passed in pairs as varargin are assigned if not
% provided as input.
innames = in(1:2:end);
for i = 1:2:numel(varargin)
idx = regexpcell(innames,varargin{i});% (see fileexchange)
if not(isempty(idx))
assignin('caller',varargin{i}, in{2*idx});
else
assignin('caller',varargin{i}, varargin{i+1});
end
end
%%%%%%%%%%%%% I call this function at the beginning of another one to define default values for 'key' value pairs. For instance, in a function like this:
function test(data,varargin)
setdefvarargin(varargin,'key1',1,'key2','default','key3',[])
% so that default values are assigned to key1, key2 and key3
% if they are not provided as key-value pairs in varargin
key1
key2
key3
Now the problem arises if any key has the name of a function in the path. I tried for instance with
setdefvarargin(varargin,'event',[],'type','fix','transform',[],'isfact',[]);
Because type is a matlab function, when later in the code, I have
switch type
case 'fix'
% some commands
case 'rand'
% some other commands
end
I get the following error.
Error using type
Too many output arguments.
I fixed the issue by entering
type = [];
before the setdefvarargin line but it's not really clean...
Any comment here is welcome. Thanks.

Respuestas (1)

Matt J
Matt J el 5 de Mzo. de 2014
Editada: Matt J el 7 de Mzo. de 2014
It's a well-known problem with assignin and other functions that create variables non-explicitly. That's why creating variables inexplicitly using assigin, eval, load, etc... is always discouraged. I recommend the attached file instead.
I also recommend you consider this FEX tool
for unpacking the structures created with the attached file into separate variables, if that's what you prefer to do.

Categorías

Más información sobre Debugging and Analysis en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by