如何通过Matlab函数将特定值保存到工作区中? [英] How to save a particular value onto workspace from Matlab function?
问题描述
我有一个m文件,其中包含几个文件,并且我了解使用函数时,这些函数中使用的变量不会保存到Matlab的工作区中.我需要做的就是在Matlab中保存一个变量.有什么方法可以做到这一点?
I have an m file, which contains several files and I understand that when using functions, the variables used within those functions are not saved to the workspace in Matlab. All I need is to save one single variables within Matlab. What are the ways to go about doing this?
推荐答案
有两种方法可以在基本工作区中保存变量,即使用 setappdata 以及 getappdata
Here are 2 ways you can save a variable in the base workspace, i.e. using assignin or setappdata along with getappdata
让我们创建一个虚拟函数来对其进行测试(不要将其命名为assignin,因为这会引起麻烦):
Let's create a dummy function to test it (do not name it assignin as it will cause trouble):
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,如下所示:
And then if you want to access B in the workspace, you can use getappdata like so:
BinWorkspace = getappdata(0,'B') %// Use the same name as in the function/call to setappdata.
请注意,在制作用于调用外部函数的GUI时,setappdata/getappdata非常有用.它允许轻松地在回调之间共享数据.
Note that setappdata/getappdata are quite useful when making GUIs in which you call external functions; it allows to easily share data between callbacks.
希望有帮助!
这篇关于如何通过Matlab函数将特定值保存到工作区中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!