|
Hi Matlab gurus!
I have made a routine called EXPLODE which works basically like the
PHP function EXTRACT (this one is more violent *hehe*). It works in
the same way: It import variables into the current workspace from a
struct.
(Please have a look at explode.m [attached below] before continuing)
The routine is supposed to work like this:
>> foo.x=1;
>> foo.debug=1;
>> explode(foo)
>> which x
x is a variable.
>> x
x =
1
>> which debug
debug is a variable.
>> debug
debug =
1
>>
The problem is that assignin('caller','debug',1); does not work from
all caller environments. Maybe because 'debug' is a restricted
variable name. (debug.m is found in PATH).
As we saw, the explode routine works when I call it from the base
workspace, but not when I use it from a subroutine, like
test_explode.
(And now, please have a look at test_explode.m)
I run the test_explode function and I get this:
>> test_explode
foo =
x: 1
foo =
x: 1
debug: 1
x is a variable.
debug is a variable.
x=1
??? Attempt to execute SCRIPT debug as a function:
/pkg/matlab/r2008b/toolbox/matlab/codetools/debug.m
Error in ==> test_explode at 8
disp(['debug=' num2str(debug)])
>>
Can anyone help me solve this "non-problem"? I want to at least *be
able to* use debug as a variable name in he sense I showed above. And
I definitely do not want Matlab to lie to me (the result of "which"
is wrong.)
Thank you!
/Henrik Holst, Sweden
explode.m
=========
function explode(varargin)
%EXPLODE Expand a struct in the caller workspace
% EXPLODE(STRUCT,...)
%
% foreach FIELD in STRUCT
% assign variable FIELD in caller workspace the value from STRUCT.FIELD
% end
%
% If multiple STRUCTs are are passed, they are expanded sequentally.
for n = 1:nargin
struct = varargin{n};
if ~isstruct(struct)
error(['argument ' num2str(k) ' is not a structure'])
end
names = fieldnames(struct);
for k = 1:length(names)
name = names{k};
evalin('caller',[name,'=[];']); % not needed?
assignin('caller',name,getfield(struct,name));
end
end
test_explode.m
==============
function test_explode
foo.x = 1
foo.debug = 1
explode(foo)
which x
which debug
disp(['x=' num2str(x)])
disp(['debug=' num2str(debug)])
--
Henrik Holst, Sweden | TYPING IS NO SUBSTITUTE FOR THINKING
holst CHR(64) nada.kth.se | - A Manual for BASIC,
http://www.nada.kth.se/~holst/ | Darthmouth College, 1 October 1964
|