如何在Matlab中为几个函数声明全局变量?
我有一个名为如何在Matlab中为几个函数声明全局变量?,matlab,variables,global,Matlab,Variables,Global,我有一个名为histShape.m的文件,其中包含一个函数histShape,还有一些其他函数 该准则的总体观点如下: % function [outputImage] = histShape(srcimg, destimg) PIXELS = 255 + 1; .... .... end % function [outputImage] = normalizeAndAccumulate(inputImage) PIXELS = 255 + 1;
histShape.m
的文件,其中包含一个函数histShape
,还有一些其他函数
该准则的总体观点如下:
%
function [outputImage] = histShape(srcimg, destimg)
PIXELS = 255 + 1;
....
....
end
%
function [outputImage] = normalizeAndAccumulate(inputImage)
PIXELS = 255 + 1;
....
....
end
%
function [pixels] = getNormalizedHistogram(histogram , inputImage)
PIXELS = 255 + 1;
....
....
end
我可以使用全局x y z代码>但我正在寻找一种不同的方式
我想将变量PIXELS
声明为全局变量,如何才能做到这一点
关于您可以使用关键字global
访问MATLAB函数中的全局变量:
function my_super_function(my_super_input)
global globalvar;
% ... use globalvar
end
您通常会在函数外部的脚本中使用相同的关键字声明全局变量:
% My super script
global globalvar;
globalvar = 'I am awesome because I am global';
my_super_function(a_nonglobal_input);
然而,这并不是绝对必要的。只要全局变量的名称在函数之间保持一致,只需定义global globalvar,就可以共享同一个变量代码>在您编写的任何函数中
你需要做的就是定义全局像素代码>在每个函数的开头(在为其赋值之前)
请参阅官方文档。除了通常不希望使用全局变量之外,另一种方法是将像素变量传递给每个函数。如果你有很多,那么你可以制作一个结构来保存它们
%
function [outputImage] = histShape(srcimg, destimg, PIXELS)
....
....
end
%
function [outputImage] = normalizeAndAccumulate(inputImage, PIXELS)
....
....
end
%
function [pixels] = getNormalizedHistogram(histogram , inputImage, PIXELS)
....
....
end
或者使用结构
%In the main script calling the functions
options.Pixels = 255 + 1
function [outputImage] = histShape(srcimg, destimg, options)
PIXELS = options.Pixels;
....
....
end
%etc...
如果在问题中使用globals的唯一原因与发布的代码有关,那么最好的解决方案是使用globals。您只需将示例的第一个结尾
移动到文件的最底部即可
function [outputImage] = histShape(srcimg, destimg)
PIXELS = 255 + 1;
function [outputImage] = normalizeAndAccumulate(inputImage)
PIXELS = 255 + 1;
end
function [pixels] = getNormalizedHistogram(histogram , inputImage)
PIXELS = 255 + 1;
end
end
如果可以避免,请不要使用全局变量。是的,但全局变量不与其他函数共享,这就是问题所在。.此解决方案与原始答案不正确(或不再正确)。@Stefan Karlsson给出了正确的解决方案,即嵌套函数。与其使用全局变量,不如将范围变量作为函数参数传递。请参阅我的答案以获取示例。