declaration of global variables
Afficher commentaires plus anciens
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)
Réponse acceptée
Plus de réponses (1)
John D'Errico
le 21 Juil 2017
Modifié(e) : John D'Errico
le 21 Juil 2017
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 commentaire
Stephen23
le 21 Juil 2017
+1 correct and entertaining, as always.
Catégories
En savoir plus sur Startup and Shutdown dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!