How to use global variables inside a function?

1,080 ビュー (過去 30 日間)
Saraswatula Sai Pavan Sastry Sastry SOME
編集済み: Image Analyst 2021 年 10 月 26 日
I have declared a global variable outside function. When I wish to use that global variable within a function(without giving it as an input argument), MATLAB is giving an error.

回答 (2 件)

Basil C.
Basil C. 2018 年 9 月 27 日
First you need to define a variable say x as global
global x
x=5
Then in the function definition which is using the global variable x just add the following line and you should be good to go
function A=hello()
global x
A= 5*x;
end
  2 件のコメント
Daniela Ardila Ospina
Daniela Ardila Ospina 2021 年 6 月 26 日
Thank you so much!
tuan nguyen minh
tuan nguyen minh 2021 年 10 月 26 日
oh thanks so much, your answer helps me

サインインしてコメントする。


Image Analyst
Image Analyst 2018 年 9 月 27 日
編集済み: Image Analyst 2021 年 10 月 26 日
It works for me. Did you declare the variable as global inside the function? You have to. If you did, then you must have a "clear all" or "clear global" in your function. Get rid of the clear statement and it will work.
See informative comments below in the code:
% Main.m
global y;
y = 10;
out1 = func1(7)
out2 = func2(9)
%==================================================================================
% func1.m -- can see y. Declared y global so this function can see it.
function out = func1(z)
global y; % Declare y as global at beginning so the rest of the function can see it.
z = y; % Will NOT throw an error because y is declared global inside func1().
%==================================================================================
% func2.m -- can NOT see y. NOT declared y global so this function can NOT see it.
function out = func2(z)
z = y; % Will throw an error because y is not declared global inside func2().
%==================================================================================
% func3.m -- can NOT see y. NOT declared y global so this function can NOT see it.
function out = func3(z)
global y; % Declare y as global at beginning so the rest of the function can see it.
clear global % DO NOT do this. Doing this will remove the ability of func3() to be able to see y!!!
z = y; % Will throw an error because y is not longer seen inside func3().

カテゴリ

Help Center および File ExchangeVariables についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by