フィルターのクリア

How do I use a variable assigned in one function to call another function?

16 ビュー (過去 30 日間)
Neil
Neil 2022 年 10 月 8 日
回答済み: Davide Masiello 2022 年 10 月 8 日
I am trying something similar to
global a
a = 5
global b
b = 10
name1(a, b)
name2(x, b)
function[x] = name1(a, b)
global a
global b
x = a + b
end
function[y] = name2(c, d)
global b
y = x + b
end
Do I need to make variable x global inside of a function or something else? I tried setting it global inside and outside of the function and I still couldn't call function y with variable x. What am I doing wrong?

採用された回答

dpb
dpb 2022 年 10 月 8 日
Forget global exists; for virtually all cases, it's not the better solution. Instead, use the return values your function(s) calculate and pass the result of the first to the second.
NOTA BENE: Functions have their own name space; arguments in the function definition are "dummy" arguments that are known by name only within the context of the function; naming them as something in the calling workspace has no bearing whatever on what their values will be at run time; they're only associated with an actual value by the linkage from the calling statement.
a = 5;
b = 10;
c=name1(a, b);
d=name2(c, b)
d = 25
NOTA BENE SECOND:
That the result of a function call can be used as the argument to another function -- the above is the same as
d=name2(name1(a,b), b)
d = 25
function[x] = name1(a, b)
x = a + b;
end
function[y] = name2(a,b)
y = a + b;
end

その他の回答 (1 件)

Davide Masiello
Davide Masiello 2022 年 10 月 8 日
The code does not global variables at all
a = 5;
b = 10;
x = name1(a,b)
x = 15
y = name2(x,b)
y = 25
function out = name1(var1,var2)
out = var1 + var2;
end
function out = name2(var1,var2)
out = var1 + var2;
end

カテゴリ

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

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by