JAN
JAN

Reputation: 21855

How can I declare a global variable in Matlab for a few functions?

I have a file called histShape.m with a function histShape , and some other functions also .

A general view of the code is :

%
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

I can use global x y z; but I'm looking for a different way .

I want to declare the variable PIXELS as global , how can I do that ?

Regards

Upvotes: 5

Views: 19979

Answers (3)

Stefan Karlsson
Stefan Karlsson

Reputation: 1085

If the only reason for using globals in the question is related to the code posted, then the best solution is to use nested functions. All you have to do is move the first end of your example to the very bottom of the file and you are done.

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

never use global variables if you can avoid it.

Upvotes: 2

Dan
Dan

Reputation: 45741

An alternative to generally undesirable use of global variables is just to pass in your PIXELS variable to each function. If you have many then you could make a struct to hold them.

%
function [outputImage] = histShape(srcimg, destimg, PIXELS)

     ....
     ....
end



%
function [outputImage] = normalizeAndAccumulate(inputImage, PIXELS)

....
....

end

%
function [pixels] = getNormalizedHistogram(histogram , inputImage, PIXELS)

  ....
  ....

end

Or with a struct

    %In the main script calling the functions
    options.Pixels = 255 + 1

    function [outputImage] = histShape(srcimg, destimg, options)

         PIXELS = options.Pixels;
         ....
         ....
    end
    %etc...

Upvotes: 4

dinkelk
dinkelk

Reputation: 2786

You can gain access to a global variable inside a MATLAB function by using the keyword global:

function my_super_function(my_super_input)
    global globalvar;

    % ... use globalvar
end

You will usually declare the global variable in a script outside the function using the same keyword:

% My super script
global globalvar;
globalvar = 'I am awesome because I am global';
my_super_function(a_nonglobal_input);

However, this is not strictly necessary. As long as the name of the global variable is consistent between functions, you can share the same variable by simply defining global globalvar; in any function you write.

All you should need to do is define global PIXELS; at the beginning of each of your functions (before you assign a value to it).

See the official documentation here.

Upvotes: 10

Related Questions