如何在Matlab中为一些函数声明一个全局变量?

时间:2012-11-14 05:33:04

标签: matlab variables global

我有一个名为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

我可以使用global x y z;,但我正在寻找另一种方式。

我想将变量PIXELS声明为全局,我该怎么做?

此致

3 个答案:

答案 0 :(得分:12)

您可以使用关键字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;即可共享同一个变量。

您需要做的就是在每个函数的开头定义global PIXELS;(在为其赋值之前)。

请参阅官方文档here

答案 1 :(得分:4)

通常不希望使用全局变量的替代方法就是将PIXELS变量传递给每个函数。如果你有很多,那么你可以制作一个结构来保存它们。

%
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...

答案 2 :(得分:1)

如果在问题中使用全局变量的唯一原因与发布的代码有关,那么最好的解决方案是使用nested functions。您所要做的就是将示例的第一个end移到文件的最底部,然后就完成了。

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
如果可以避免,

永远不会使用全局变量。