MATLAB: Nested function not assigning value to global variable

global variablesubfunction

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?

Best Answer

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