Nested function not assigning value to global variable

조회 수: 3 (최근 30일)
Pal Szabo
Pal Szabo 2017년 9월 1일
댓글: John D'Errico 2017년 9월 1일
My main script invites a subfunction, which then invites different subfunctions. I want these subfunctions to modify global variables. A simpified example:
a=9;
b=2;
global p
myfunc(a,b);
display Result:
p
function [varargout] = myfunc(a,b);
arr=[a;b];
varargout={arr};
end
mysecondfunction(arr);
prod = arr(1)*arr(2);
p = prod;
end
When the main script calls p again it is empty. Why is this so and how can I fix it?
  댓글 수: 3
Pal Szabo
Pal Szabo 2017년 9월 1일
I'm trying to avoid them and write better code, now I've run into this problem and interested how to solve it.
John D'Errico
John D'Errico 2017년 9월 1일
UGH!!!!!!! Ugly, nasty code.
You solve the problem most easily by not using globals at all.
It is a bad idea to use globals in the first place. This is yet another reason why. You don't need globals. Most new users think they do, and eventually learn why not. But they make for nasty, bad code that will be difficult to debug.
As bad an idea is to use variables named prod, or other names that are already used for function names. When you name them that, the function prod will no longer work properly.

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

채택된 답변

KSSV
KSSV 2017년 9월 1일
You have to assign p...you have not yet assigned it.
a=9;
b=2;
global p
p = rand ;
myfunc(a,b);
display Result:
p
function [varargout] = myfunc(a,b);
arr=[a;b];
varargout={arr};
end
mysecondfunction(arr);
prod = arr(1)*arr(2);
p = prod;
end
  댓글 수: 3
KSSV
KSSV 2017년 9월 1일
I was thinking you want to make a global variable in the main code and use it in every function without passing it....your criteria is different.....in this case....call it as a output from the function..not a global variable...
Pal Szabo
Pal Szabo 2017년 9월 1일
Alright, thanks!

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

추가 답변 (1개)

Stephen23
Stephen23 2017년 9월 1일
편집: Stephen23 2017년 9월 1일
Get rid of the global.
Globals do not solve anything, no matter how much beginners love using them.
It is not clear what your (buggy, non-working, incomplete) code is supposed to do, but making a nested function work correctly is very simple _when you avoid using evil global:
function p = test2
p = [];
myfunc(9,2);
function myfunc(varargin);
p = prod([varargin{:}]);
end
end
and tested:
>> test2()
ans = 18
And remember in future: if you even think of using global then your code design needs to be improved.

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by