MATLAB: Declaration of global variables

global variable

Hello, I think I have declared global variable correctly but it keeps saying "Error: File: Ex3_6.m Line: 10 Column: 16 The GLOBAL or PERSISTENT declaration of "n" appears in a nested function, but should be in the outermost function where it is used." I declared it in the outermost function.
Can you guys help me?
==============================================
function [avg,med]=Ex3_6(in)
global n
n=length(in);
avg=newmean(in);
med=newmedian(in);
function a=newmean(in)
global n
a=sum(in)/n;
end
function m=newmedian(v)
global n
w=sort(v);
if rem(n,2)==1
m=w((n+1)/2);
else
m=(w(n/2)+w(n/2+1))/2;
end
end
end
=================================
And I run below.
=====================================
score= score=[87 75 98 100 45 37 73];
[avg,med]=Ex3_6(score)

Best Answer

The proper syntax is to define the subfunctions outside of the "function ... end" construct:
function [avg,med]=Ex3_6(in)
global n
n=length(in);
avg=newmean(in);
med=newmedian(in);
end
function a=newmean(in)
global n
a=sum(in)/n;
end
function m=newmedian(v)
global n
w=sort(v);
if rem(n,2)==1
m=w((n+1)/2);
else
m=(w(n/2)+w(n/2+1))/2;
end
end