MATLAB Answers

Defining global variables to be used in a function and outside

584 views (last 30 days)
Sulaiman Qureshi
Sulaiman Qureshi on 4 Mar 2019
Answered: Sayyed Ahmad on 16 Jun 2020
Hi,
So I have a script where I have a function, with a variable, say A=100. Thats fine, but outside this function in the same script this variable is also needed. So I define it again. Is it possible to only have to define the variable once so that I don't need to do it twice?
Thanks
  2 Comments

Sign in to comment.

Answers (3)

Walter Roberson
Walter Roberson on 7 Mar 2019
Suppose that you had code that securely processed credit card information in a function . Should anyone be able to force access to your credit card information just by declaring a global variable with the same name as the local variable used by the function to store your card number ?
No reasonable programming language would permit someone to come along later and hijack all local use of a variable name .
If this is something that you feel strongly should be supported then you can get a copy of the source code for Octave and hack it to have it look every variable up in the global name table, and watch the fireworks the first time that some does a
global i; i = []
Remember that variables take priority over functions so this will force every use of i as the imaginary unit to make the expression empty instead ....

Anant Upadhyay
Anant Upadhyay on 7 Mar 2019
Hi Sulaiman,
Usually, 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. Any change of value to that variable, in any function, is visible to all the functions that declare it as global.
You can look the following code for more reference:
setGlobalx(1138)
r = getGlobalx
% Function setting the value of Global variable “x”
function setGlobalx(val)
global x
x = val;
end
% Function returning the value of global variable “x”
function r = getGlobalx
global x
r = x;
end

Sayyed Ahmad
Sayyed Ahmad on 16 Jun 2020
I think following code can help you:
classdef hC < handle
properties
var
end
end
your function wold look like
function [output] = testfun(input1,input2)
input1.var= input1.var+input2;
output = input1.var.^2;
end
now try this:
>> a=hC
a =
hC with properties:
var: []
>> a.var=100
a =
hC with properties:
var: 100
>> b=testfun(a,10)
b =
12100
>> a
a =
hC with properties:
var: 110
instance of a handle class points to the original data. If some changes happens in an instance, this changes them in the original one.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by