简体   繁体   中英

Using variables from one Octave function file in another

Say I have two Octave function files in the same load path: file1.m and file2.m.

file1:

function [variable] = file1()
    variable = 1;
endfunction

file2:

function file2()
    variable2 = variable*2;
endfunction

How can I make it so that I can use variable in file2?

I have tried many things, such as:

1.

function [variable] = file1()
    global variable = 1;
endfunction

function file2()
    global variable;
    variable2 = variable*2;
endfunction

2.

Calling file1() before or within file2() in file2.m

file1();
function file2()
    global variable;
    variable2 = variable*2;
endfunction

3.

Using variable as a parameter when calling file2()

function file2(variable)
    variable2 = variable*2;
endfunction

with no success. Any help would be greatly appreciated!

The easiest solution would be to call file1 in file2 :

function file2()
    variable = file1();
    variable2 = variable*2; % do you want to return variable2 as the output of file2?
endfunction

EDIT

If your function returns more than one variable, the process is exactly the same, ie:

function [x,y,z] = file1()
    x = 1;
    y = 2;
    z = 3;
endfunction

function file2()
    [x,y,z] = file1();
    variable2 = 2*(x+y+z); % do you want to return variable2 as the output of file2?
endfunction

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM