【发布时间】:2014-10-14 22:23:00
【问题描述】:
我有一个 m 文件,其中包含多个文件,并且我知道在使用函数时,这些函数中使用的变量不会保存到 Matlab 的工作区中。我只需要在 Matlab 中保存一个变量。有什么方法可以做到这一点?
【问题讨论】:
标签: matlab
我有一个 m 文件,其中包含多个文件,并且我知道在使用函数时,这些函数中使用的变量不会保存到 Matlab 的工作区中。我只需要在 Matlab 中保存一个变量。有什么方法可以做到这一点?
【问题讨论】:
标签: matlab
您可以通过以下两种方式在基础工作区中保存变量,即使用assignin 或setappdata 以及getappdata
让我们创建一个虚拟函数来测试它(不要将它命名为assignin,因为它会引起麻烦):
function Test_Assignin(~) %// Dummy function
clear
clc
A =rand(10);
assignin('base','AinWorkspace',A); %/ Assign the variable A (local to the function) to the variable named 'AinWorkspace' in the 'base' workspace, which you can access after running the function.
B = A/2; %// Generate other variable
setappdata(0,'B',B); %// use setappdata to make the variable available to the base workspace (hence the 0 at the beginning), and in your command window use getappdata. (See below).
end
然后如果你想在工作区访问 B,你可以像这样使用 getappdata:
BinWorkspace = getappdata(0,'B') %// Use the same name as in the function/call to setappdata.
请注意,在制作调用外部函数的 GUI 时,setappdata/getappdata 非常有用;它允许在回调之间轻松共享数据。
希望有帮助!
【讨论】:
您可以选择声明该特定变量global:
function foo(k)
var1=2*k;
global var1;
end
【讨论】: