declaration of global variables
이전 댓글 표시
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)
채택된 답변
추가 답변 (1개)
John D'Errico
2017년 7월 21일
편집: John D'Errico
2017년 7월 21일
I'm sorry, but this is just about the silliest reason to use a global variable I've ever seen.
n is declared as global because you don't want to pass in n as an argument to the function, perhaps because you think this is more efficient?
Worse, these are nested functions. You never needed to pass in n at all, or make it global, since they can see the variables in the workspace of the caller.
A common result of globals is buggy code. What do you have? Buggy code. Surprise.
Were you told you had to use global variables as part of this assignment? I hope not, since then your teacher would be teaching you tools you should be avoiding in the first place. Far better they should be showing you how to pass data around properly.
function [avg,med]=Ex3_6(in)
n=length(in);
avg=newmean(in);
med=newmedian(in);
function a=newmean(in)
a=sum(in)/n;
end
function m=newmedian(v)
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
As you can see above, I never defined n as global, and since those are nested functions, they can see n.
Or, you could have made them subfunctions. In that case, pass in n as an argument, or as good, it hurts nothing if you just obtain the value of n in each subfunction from the vector passed in.
댓글 수: 1
Stephen23
2017년 7월 21일
+1 correct and entertaining, as always.
카테고리
도움말 센터 및 File Exchange에서 Performance and Memory에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!