Getting the x from a function file to call inside another function file

2 Ansichten (letzte 30 Tage)
Hi there i need help, i have written a function file lets say
[m,c]=myfunction(x,y) where i defined the x and y inside this function file,
in a seperate function file, lets says [y]=myfunction2(m,c)
How can i defined the x and y i have called/defined in the previous function file
Note, i need to call this x again back to get the length for the n to be run within the function file myfunction2
  1 Kommentar
Jan
Jan am 20 Mär. 2021
"written a function file lets say [m,c]=myfunction(x,y) where i defined the x and y inside this function file" - this is not clear yet. It seems like x and y are inputs of this function and not defined inside. Posting some working code is always the best idea.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Jan
Jan am 20 Mär. 2021
The reliable way to provide the values of variables defined inside a function is to export them as output arguments. If they are need inside other functions, forward them as input arguments:
function main
c = rand;
[a, x, y] = fcn1(c)
fcn2(a, x, y)
end
function [a, x, y] = fcn1(c)
x = 1 - c;
y = c^2;
a = x - y;
end
function [b] = fcn2(a, x, y)
a
x
y
end
You could use nested functions also, but this increases the complexity of the code also. GLOBAL variables can share variables between functions also, but they are a shot in your knee and a bad programming practize, because they are very hard to debug.

Weitere Antworten (0)

Kategorien

Mehr zu Scope Variables and Generate Names finden Sie in Help Center und File Exchange

Produkte


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by