gpt4 book ai didi

matlab - 无法更新 Matlab 中的类定义

转载 作者:太空宇宙 更新时间:2023-11-03 19:52:33 25 4
gpt4 key购买 nike

我在使用 Matlab 时遇到了一个恼人的问题,一个 earlier answer不幸的是,显然同样的问题对我没有帮助。很抱歉这个问题太长了——你需要很多信息来重现这个问题(我试着尽可能地删减它……)

问题是这样的:无论我做什么,在我使用了一个类后我都不能“让 Matlab 忘记”。使用的值似乎是持久的,并且对类定义的编辑不会“坚持”。在后一种情况下,错误消息是:

Warning: The class file for 'myClass' has been changed; but the change cannot be applied because objects based on the old class file still exist. If you use those objects, you might get unexpected results. You can use the 'clear' command to remove those objects. See 'help clear' for information on how to remove those objects.

我什至在

>> clear all
>> clear functions
>> clear ans

尽管我尝试清除类定义,但不知何故类定义仍然存在。更糟糕的是,当我修改类的一个实例的值,然后清除它时,该值不会以某种方式被“遗忘”。为了说明这一点,这里是 myClass 的源代码:

% a simple class definition that shows the problem that I cannot
% figure out how to redefine a class without restarting Matlab
classdef myClass < handle
properties
precursors = {'none'};
numPre = {1};
value = 1;
end

methods
function obj = myClass(pre, num, val)
% constructor
if nargin > 0
obj.precursors = pre;
obj.numPre = num;
obj.value = val;
end
end
function v = sumVal(obj)
% find the sum of the value of all precursors
n = numel(obj.precursors);
v = 0;
for ii = 1:n
pc = obj.precursors{ii};
if isa(pc, 'myClass')
if ii==1
v = 0;
end
v = v + sumVal(pc) * obj.numPre{ii};
else
v = obj.value;
end
end
end
end

% only the following named instances may exist:
enumeration
grandpa ({'none'}, {1}, 1)
father ({myClass.grandpa}, {3}, -1)
son ({myClass.father}, {2}, -1)
end
end

在 Matlab 的新实例中,我执行以下操作:

>> son = myClass.son;
>> sumVal(son)

ans =

6

>> grandpa = myClass.grandpa;
>> grandpa.value = 5;
>> sumVal(son)

ans =

30

到目前为止,还不错。 sumVal 函数发现了父亲和祖父,并且 sumVal 计算正确(第一种情况为 6 * 1,第二种情况为 6 * 5)。

现在我删除“一切”(我认为):

>> clear all
>> clear functions
>> clear ans

我只创建一个变量:

>> son = myClass.son;

现在更重要的是——意想不到的答案

>> sumVal(son)

ans =

30

当我检查加载的变量时,我发现

>> whos
Name Size Bytes Class Attributes

son 1x1 112 myClass

没有grandpa实例,也没有触及类定义文件。然而,grandpa(我创建,然后删除)的值在某种程度上是持久的。

当我对 myClass.m 文件做一个小改动,并尝试创建一个新变量时(在 clear all 之后),我得到了显示的消息多于。所有这些都引出了我的问题:

Matlab 在哪里隐藏了我的类的实例,以便变量在 clear all 后保持不变,以及如何清除工作区(无需重新启动)以便“重置”类定义?

我不知道这是否重要,但我使用的是 Matlab 7.14.0.739 (R2012a)

最佳答案

您有一个未被 MATLAB 销毁的中间实例 myClass.father。你必须自己删除

>> clear grandpa
>> delete(son.precursors{1})
>> clear son
>> clear classes
>> son = myClass.son
son =
son
>> sumVal(son)
ans =
6

编辑:或者,您可以向类中添加析构函数

    function delete(obj)
if isa(obj.precursors{1}, 'myClass')
delete(obj.precursors{1});
end
end

并使用 delete(son) 而不是将其留给 clear 函数来销毁。您可以将其扩展到您的案例并递归删除树中的所有实例。

关于matlab - 无法更新 Matlab 中的类定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17242237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com