필터 지우기
필터 지우기

define variable inside functions

조회 수: 29 (최근 30일)
Ben Wang
Ben Wang 2011년 8월 2일
Dear all:
I parse a structure into a function, which build the system matrix for a model. The code looks something like this:
function [m] = test(param)
%%SETUP GLOBAL PARAMETERS
F = fieldnames(param);
for i = 1:length(F)
field = F{i};
assignin('caller', field, param.(field));
end
%%SET UP MATRICES FOR SOLVING THE MODEL
m = [kappa, alpha];
end
The structure param looks like the following:
param.kappa = 0.8;
param.alpha = 1;
but when I run the function test, matlab returns the following complain:
??? Undefined function or variable 'kappa'.
I would imagine 'assignin' assigns the value into the kappa, so kappa should be automatically defined, but this is not the case. If I take away kappa and just leave alpha in the matrix, matlab complains about alpha is not defined. Any ideas why this happens?
PS: The reason I do this is not obvious in this simplified function. My model is very complex and involves changing parameters in simulations, so I want to remain the variable name as their name rather than some vector/matrix index to minimise errors.
Thanks alot in advance!
Cheers Ben
  댓글 수: 1
Oleg Komarov
Oleg Komarov 2011년 8월 2일
As mentioned in your previous post I don't see the need for what you're doing since you're hardcoding m.
m = [param.kappa param.alpha];
And btw you already have an error...

댓글을 달려면 로그인하십시오.

채택된 답변

Jan
Jan 2011년 8월 2일
The documentation of ASSIGNIN reveals, that the variable is created in the caller. Therefore the program would run as:
function m = MainProgram(param)
test(param); % Call the subfunction to create the variables
% SET UP MATRICES FOR SOLVING THE MODEL
m = [kappa, alpha];
end
function test(param) % The subfunction
F = fieldnames(param);
for i = 1:length(F)
field = F{i};
assignin('caller', field, param.(field));
end
As you can see, the confusion level of automagically created variables is very high. I strongly recommend to avoid such tricks, if you are not an advanced programmer and know exactly what you are doing. If you are a beginner, such Voodoo techniques will waste your time. Faster, nicer, easier and stable:
function m = MainProgram(param)
% SET UP MATRICES FOR SOLVING THE MODEL
m = [param.kappa, param.alpha];
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by