assignin 'caller' fails when variable is a matlab function in the path
조회 수: 7 (최근 30일)
이전 댓글 표시
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.
댓글 수: 0
답변 (1개)
Matt J
2014년 3월 5일
편집: Matt J
2014년 3월 7일
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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Debugging and Analysis에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!