在matlab中,我用class和out的方法得到了不同的值
在matlab中,我定义了一个类,并在另一个脚本中实例化了该类,但我在方法中得到了不同的值。我的matlab代码如下所示: 测试添加.m在matlab中,我用class和out的方法得到了不同的值,matlab,Matlab,在matlab中,我定义了一个类,并在另一个脚本中实例化了该类,但我在方法中得到了不同的值。我的matlab代码如下所示: 测试添加.m classdef test_add properties a b end methods function obj = test_add(a, b) obj.a = a; obj.b = b; end func
classdef test_add
properties
a
b
end
methods
function obj = test_add(a, b)
obj.a = a;
obj.b = b;
end
function c = add_1(obj)
c = obj.a + 1;
end
function inter(obj, t)
for i = 1:t
obj.a = obj.add_1();
end
fprintf('In the method:\n');
fprintf('a = %d\n',obj.a);
fprintf('b = %d\n',obj.b);
disp('=======================');
end
end
end
tt = test_add(1,2);
tt.inter(3);
fprintf('Out of the method:\n');
fprintf('a = %d\n',tt.a);
fprintf('b = %d\n',tt.b);
classdef test_add < handle
...
end
main.m
classdef test_add
properties
a
b
end
methods
function obj = test_add(a, b)
obj.a = a;
obj.b = b;
end
function c = add_1(obj)
c = obj.a + 1;
end
function inter(obj, t)
for i = 1:t
obj.a = obj.add_1();
end
fprintf('In the method:\n');
fprintf('a = %d\n',obj.a);
fprintf('b = %d\n',obj.b);
disp('=======================');
end
end
end
tt = test_add(1,2);
tt.inter(3);
fprintf('Out of the method:\n');
fprintf('a = %d\n',tt.a);
fprintf('b = %d\n',tt.b);
classdef test_add < handle
...
end
输出:
In the method:
a = 4
b = 2
=======================
Out of the method:
a = 1
b = 2
这是一个值类与句柄类的问题,解决方案是: 测试添加.m
classdef test_add
properties
a
b
end
methods
function obj = test_add(a, b)
obj.a = a;
obj.b = b;
end
function c = add_1(obj)
c = obj.a + 1;
end
function inter(obj, t)
for i = 1:t
obj.a = obj.add_1();
end
fprintf('In the method:\n');
fprintf('a = %d\n',obj.a);
fprintf('b = %d\n',obj.b);
disp('=======================');
end
end
end
tt = test_add(1,2);
tt.inter(3);
fprintf('Out of the method:\n');
fprintf('a = %d\n',tt.a);
fprintf('b = %d\n',tt.b);
classdef test_add < handle
...
end
这是一个值类与句柄类的问题,解决方案是: 测试添加.m
classdef test_add
properties
a
b
end
methods
function obj = test_add(a, b)
obj.a = a;
obj.b = b;
end
function c = add_1(obj)
c = obj.a + 1;
end
function inter(obj, t)
for i = 1:t
obj.a = obj.add_1();
end
fprintf('In the method:\n');
fprintf('a = %d\n',obj.a);
fprintf('b = %d\n',obj.b);
disp('=======================');
end
end
end
tt = test_add(1,2);
tt.inter(3);
fprintf('Out of the method:\n');
fprintf('a = %d\n',tt.a);
fprintf('b = %d\n',tt.b);
classdef test_add < handle
...
end
在Matlab中有两种类型的类:句柄类和值类。如果你什么也没说,你就得到了值。大多数面向对象语言都使用句柄类语义 因此,您有两种选择:
classdef test_add < handle
在Matlab中有两种类型的类:句柄类和值类。如果你什么也没说,你就得到了值。大多数面向对象语言都使用句柄类语义 因此,您有两种选择:
classdef test_add < handle