Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 467
JAN Avatar asked Nov 14 '12 05:11

JAN


People also ask

Can functions use global variables MATLAB?

Ordinarily, each MATLAB® function has its own local variables, which are separate from those of other functions and from those of the base workspace. However, if several functions all declare a particular variable name as global , then they all share a single copy of that variable.

What's the best way to declare and define global variables and functions?

The clean, reliable way to declare and define global variables is to use a header file to contain an extern declaration of the variable. The header is included by the one source file that defines the variable and by all the source files that reference the variable.


1 Answers

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.

like image 142
dinkelk Avatar answered Oct 15 '22 05:10

dinkelk