假设我在同一个加载路径中有两个Octave函数文件:file1.m和file2.m。
文件1:
function [variable] = file1()
variable = 1;
endfunction
file2的:
function file2()
variable2 = variable*2;
endfunction
如何才能在文件2中使用variable
?
我尝试了很多东西,例如:
1
function [variable] = file1()
global variable = 1;
endfunction
function file2()
global variable;
variable2 = variable*2;
endfunction
2
在file2.m
中的file2()之前或之内调用file1()file1();
function file2()
global variable;
variable2 = variable*2;
endfunction
3
调用file2()时使用变量作为参数
function file2(variable)
variable2 = variable*2;
endfunction
没有成功。任何帮助将不胜感激!
答案 0 :(得分:3)
最简单的解决方案是在file1
中致电file2
:
function file2()
variable = file1();
variable2 = variable*2; % do you want to return variable2 as the output of file2?
endfunction
修改强>
如果你的函数返回多个变量,那么过程完全相同,即:
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