I still learn Matlab code, and always finding some problems related to script creation. This time I want to share about what in Matlab called “global variable”. This kind of variable at the first time did not attractive to me because I did not find the usefulness of it. Now I understand the important of understanding the global variable.
I have created some algorithms such as genetic algorithms for my dissertation. When I try to create the function having many variables, I always been annoyed with an error “undefined variable …” and I revised the code with that variable included. But the declaration seems strange to me, like this.
So, I try to solve that problem by searching in the internet. I found that I have to use global variable that used everytime when some function called the variable. Explanation in web officially from mathworks is here. For everyone who like video in youtube, this problem is explained clearly here. Now I try to fix my function using global variables, and I do not have to delcare many variables in my function.
Let’s we try some simple function. We have to create main function and other function to calculate something from main function. For example we name the main function “energy” that called other function to calculate the internal energy “calc”. Type in the command window >> edit calc to create calc.m function. The message will be opened:
Just click “Yes” because it only informed that calc.m does not exist. But becarefull if the message does not shows to us. It means the name of our function has been used in Matlab, so we have to change to other names.
Now in the same way, create new m-file for main function with the name e.g “main”. Make sure your m-file name is not Matlab built-in functions.
Now try to run the m-file by clicking the run icon (green triangle). There is an error message:
You have to include the variable c in your calc function or you have to declare that variable in your main file as global variable. Add c as our global variable in the main function. Revise your main and calc file to include global variable c:
And try to run again, you have to get the result without error message (don’t forget to save your m-file everytime you edit it). No need to include c in calc variable function anymore 🙂.
- E =
- ans =
NOTE: future of Matlab said that … Ok, I paste the warning:
Warning: The value of local variables may have been changed to match the
globals. Future versions of MATLAB will require that you
a variable to be global before you use that variable.
So, we have to declare global c first before declare c=300000000;