declaration of global variables
Mostrar comentarios más antiguos
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)
Respuesta aceptada
Más respuestas (1)
John D'Errico
el 21 de Jul. de 2017
Editada: John D'Errico
el 21 de Jul. de 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 comentario
Stephen23
el 21 de Jul. de 2017
+1 correct and entertaining, as always.
Categorías
Más información sobre Performance and Memory en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!