1

Is there any way to define a variable in main function and use it in all sub-function. enter image description here

I've tried to declare variables as global but it seems I should repeat it in all function again. I'm wonder what's the benefit of global variable at all!

use variable as global:

main program
global x
syms x
subfunc1
subfunc2
...

and

subfunc1
global x

and

subfunc2
global x

(maybe this format remind us to have global variable in function but it was better to cause error if we use same name of variable in function same as Matlab keywords) I don't want to import the variable as all function argument and don't want to declare that variable in all function again and again. any help would be appreciated.

asys
  • 667
  • 5
  • 20
  • 6
    pass it as an argumeeeeent! Using global variables is a terrible idea. Loads of MATLAB functions will use a variable named "x" inside them, and you will get your `x` overwritten everytime that happens! – Ander Biguri Dec 14 '16 at 13:42

2 Answers2

1

If you really want to have access to the same variable, then there are only two ways I know of in Matlab: nested functions(described by answer from @justthom8) and global variables. Other methods of getting data into functions exist, such as getappdata, guidata and (my personal favorite:) passing function arguments. However, these approaches make copies of variables.

Perhaps you should ask yourself why you want to avoid making copies of variables. If you are worried about performance, you should know that Matlab efficiently use variables as reference to data only, so you can safely send a variable in to a function (thereby copying the variable) without copying the actual data. its first after you modify the data inside of the function that the data is actually copied. All this is totally invisible to us, except as a possible drop in performance during alot of copying. This is called copy-on-write.

Global variables can be used to optimize Matlabs performance, by coding them in such a way as to avoid copying data, but that really requires knowing what you are doing, and it opens up for a whole lot of pitfalls, especially if your projects grow in size.

Community
  • 1
  • 1
Stefan Karlsson
  • 1,092
  • 9
  • 21
0

One thing you can do is define the other functions as subfunctions of the main function. Something like below

Both of the functions subFunc1 and subFunc2 should have access to data you define above it in mainFunc

 function mainFunc()
 variable1 = 'stuff';
 variable2 = 5;
    function subFunc1()
        %do stuff
    end

    function subFunc2()
       %do more stuff
    end
end

Edit 1

Of course you can define global data in the mainFunc that gets used in the subfunctions, but I wouldn't recommend doing that since it can get changed in unexpected ways that you don't intend for to happen.

Rethipher
  • 336
  • 1
  • 14