我在matlab
中有以下课程:
classdef floating_search
properties
S,M;
end
methods
function s = support(x,y)
for i=1:length(x)
if(y(i)~=1)
s = x(i);
end
end
end
end
end
现在,在命令winows中,我做了以下事情:
>> x=1:10;
>> floating_search.S = x;
>> y=trapmf(x,[1 3 5 9])
y =
Columns 1 through 7
0 0.5000 1.0000 1.0000 1.0000 0.7500 0.5000
Columns 8 through 10
0.2500 0 0
>> floating_search.M = y;
>> floating_search.support(floating_search.S, floating_search.M)
??? Reference to non-existent field 'support'.
对于最后一个命令,为什么我会收到此错误?我称这个功能错了吗?如何将值floating_search.S
和floating_search.M
传递给函数并检索S
的{{1}}值?
感谢。
答案 0 :(得分:2)
您永远不会初始化您的对象。 此外,我认为您应该使用代码作为非静态方法进行协调:
classdef floating_search
properties
S
M
end
methods
function s = support(obj)
for i=1:length(obj.S)
if(obj.M(i)~=1)
s = obj.S(i);
end
end
end
end
end
然后执行:
x = 1:10;
y = trapmf(x,[1 3 5 9])
myInstance = floating_search()
myInstance.S = x;
myInstance.M = y;
myInstance.support()
答案 1 :(得分:1)
你的班级缺少一个构造函数。 此外,你永远不会初始化任何对象。
您的floating_search.S = x;
语句会生成一个名为floating_search
的结构:
>> whos floating_search
Name Size Bytes Class Attributes
floating_search 1x1 256 struct
请尝试此操作(将文件另存为floating_search.m
):
classdef floating_search
properties
S;
M;
end
methods
% constructor - place to initialize things
function obj = floating_search()
end
% you need the first input argument 'obj', since this is a value class
% see http://www.mathworks.de/de/help/matlab/matlab_oop/comparing-handle-and-value-classes.html
function s = support(obj, x, y)
for i=1:length(x)
if(y(i)~=1)
s = x(i);
end
end
end
end
end
然后运行代码:
% generate your data
x = 1:10;
y = trapmf(x,[1 3 5 9]);
# initialize object
a = floating_search()
a.S = x;
a.M = y;
a.support(a.S, a.M)