检查一个变量是否存在于工作区 MATLAB 中
我们将研究不同的方法来检查 MATLAB 工作区中观察变量是否存在。
变量可以是从本地变量到函数的任何内容。我们可以使用 exist
函数和不使用函数来检查变量是否存在。
exist
函数给出从 0 到 9
的数字。每个数字都有其含义,具体取决于我们搜索的变量。
让我们从检查工作区中观察变量的存在开始,而不使用 MATLAB 中的任何内置函数。
在不使用 MATLAB 中的任何内置函数的情况下检查工作区中观察下的变量
为此,我们将根据我们的可变需求设计一个函数。让我们的变量 a
、b
、c
和 d
等于 1
。
我们将函数定义为 check_workspace_variables()
。提供给函数的参数将是我们想要查看的变量的名称。
a = 1;
b = 1;
c = 1;
d = 1;
check_workspace_variables('d')
check_workspace_variables('b')
check_workspace_variables('c')
check_workspace_variables('e')
function our_output = check_workspace_variables(variable_check)
% Check to see if a variable exists in the Base Workspace
does_string_exists = sprintf('exist(''%s'')',variable_check);
our_workspace_variables = evalin('base',does_string_exists);
if our_workspace_variables == 1 % If variable exists in our workspace in MATLAB
disp('Is Present in our Workspace')
our_output = 1 ;
else % If variable doesnot exist in our workspace in MATLAB
disp('Is Absent from our Workspace')
our_output = 0 ;
end
end
输出:
check_variable_presence
Is Present in our Workspace
ans = 1
Is Present in our Workspace
ans = 1
Is Present in our Workspace
ans = 1
Is Absent from our Workspace
ans = 0
在此示例中,如果你仔细查看代码中定义的变量,我们会检查变量 a
、b
、c
和 e
。
任何名为 e
的变量都不存在。这就是为什么三个答案返回为 1
,最后一个返回为 0
。
使用 MATLAB 中的 Exist
函数检查工作区中观察下的变量
让我们通过使用 magic()
函数创建一个随机矩阵并将其命名为 our_variable
来理解这个概念。我们将使用 exist
函数来检查 our_variable
是否存在于我们在 MATLAB 的工作区中。
our_variable = magic(5)
exist our_variable
输出:
our_variable =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
ans = 1
根据 MATLAB 中函数的预定义数值输出,1
表示我们变量的 name
存在于 MATLAB 的工作区中。
相关文章
如何在 Matplotlib Pyplot 中显示网格
发布时间:2024/02/04 浏览次数:142 分类:Python
-
本文演示了如何在 Python Matplotlib 中在一个图上画一个网格。使用 grid()函数来绘制网格,并解释了如何改变网格颜色和线条类型。
在 Matplotlib 中的图中添加文字
发布时间:2024/02/04 浏览次数:180 分类:Python
-
本教程展示了我们如何使用 plt.text()方法在 Matplotlib 中为图或轴添加文字。
如何在 Matplotlib 中的多个线条之间进行填充
发布时间:2024/02/04 浏览次数:208 分类:Python
-
`fill_between()` 每次只能填充两条线之间的区域,但是我们可以选择一对行来填充多个线条之间的区域。
如何在 Matplotlib 中画一条任意线
发布时间:2024/02/04 浏览次数:166 分类:Python
-
本教程讲解了我们如何在 Matplotlib 中使用 matplotlib.pyplot.plot()、matplotlib.pyplot.vlines()、matplotlib.pyplot.hlines()方法和 matplotlib.collection.LineCollection 绘制任意线条。
Pandas 在 Matplotlib 柱状图上绘制多列图
发布时间:2024/02/04 浏览次数:189 分类:Python
-
在本教程中,我们将探讨如何使用 `DataFrame` 对象的 `plot()` 方法在柱状图上绘制多列。
如何在 Matplotlib 中绘制数据列表的直方图
发布时间:2024/02/04 浏览次数:178 分类:Python
-
本教程介绍了如何使用 plt.hist()方法从数据列表中绘制直方图。我们可以使用 plt.hist()方法从数据列表中绘制直方图。
Matplotlib 中的叠加条形图
发布时间:2024/02/04 浏览次数:182 分类:Python
-
本教程展示了如何使用 plt.bar()方法将某些数据集的条形图堆叠在另一个数据集上。我们在 Matplotlib 中使用 matplotlib.pyplot.bar()方法生成条形图。
在 Python Matplotlib 中生成反向色彩图
发布时间:2024/02/04 浏览次数:136 分类:Python
-
本教程解释了如何反转 Python Matplotlib Plot 的 Colormap。
设置 Matplotlib 网格间隔
发布时间:2024/02/04 浏览次数:250 分类:Python
-
本教程将介绍我们如何在 Matplotlib 绘图中设置网格间距,并对主要网格和次要网格应用不同的样式。