对象可以用括号或大括号进行索引,如obj(idx)或类似obj{idx},甚至类似obj(idx).field然而,这取决于程序员来决定这个索引的实际含义。在多项式类的情况下p(n)可能意味着的系数n-多项式的次幂,或者它可能是多项式的求值n。此下标引用的含义从subsref方法
newval = subsref (val, idx) ¶对执行下标元素选择操作val根据指定的下标idx.
下标idx必须是具有字段的结构体数组type和subs’. 的有效值type是"()","{}"和"."这个subs字段可以是":"或者索引值的元胞数组。
以下示例显示如何提取矩阵的前两列
val = magic (3)
⇒ val = [ 8 1 6
3 5 7
4 9 2 ]
idx.type = "()";
idx.subs = {":", 1:2};
subsref (val, idx)
⇒ [ 8 1
3 5
4 9 ]
请注意,这与书写相同val(:, 1:2).
如果idx是一个带有字段的空结构体数组type和subsreturnval.
关键字end不能在中使用subsref用于索引赋值。
例如,此类使用的约定是"()"多项式求值并使用进行索引"{}"返回n-th系数(的n-th次幂)。的代码subsref方法看起来像
function r = subsref (p, s)
if (isempty (s))
error ("@polynomial/subsref: missing index");
endif
switch (s(1).type)
case "()"
idx = s(1).subs;
if (numel (idx) != 1)
error ("@polynomial/subsref: need exactly one index");
endif
r = polyval (fliplr (p.poly), idx{1});
case "{}"
idx = s(1).subs;
if (numel (idx) != 1)
error ("@polynomial/subsref: need exactly one index");
endif
if (isnumeric (idx{1}))
r = p.poly(idx{1}+1);
else
r = p.poly(idx{1});
endif
case "."
fld = s.subs;
if (! strcmp (fld, "poly"))
error ('@polynomial/subsref: invalid property "%s"', fld);
endif
r = p.poly;
otherwise
error ("@polynomial/subsref: invalid subscript type");
endswitch
if (numel (s) > 1)
r = subsref (r, s(2:end));
endif
endfunction
下标赋值的等效函数使用subsasgn方法
newval = subsasgn (val, idx, rhs) ¶根据指定的下标执行下标赋值操作idx.
下标idx必须是具有字段的结构体数组type和subs’. 的有效值type是"()","{}"和"."这个subs字段可以是":"或者索引值的元胞数组。
以下示例显示如何将3乘3矩阵的前两列设置为零。
val = magic (3);
idx.type = "()";
idx.subs = {":", 1:2};
val = subsasgn (val, idx, 0)
⇒ [ 0 0 6
0 0 7
0 0 2 ]
请注意,这与书写相同val(:, 1:2) = 0.
如果idx是一个带有字段的空结构体数组type和subsreturnrhs.
关键字end不能在中使用subsasgn用于索引赋值。
val = optimize_subsasgn_calls () ¶old_val = optimize_subsasgn_calls (new_val) ¶old_val = optimize_subsasgn_calls (new_val, "local") ¶查询或设置的内部标志subsasgn方法胼胝化。
如果为true,Octave将在调用时尝试消除冗余复制subsasgn方法。
当从具有的函数内部调用时"local"参数,则该变量会为函数及其调用的任何子程序在本地进行更改。退出函数时将恢复原始变量值。
详见: subsasgn.
请注意subsref和subsasgn方法总是接收整个索引链,而它们通常只处理第一个元素。这些方法负责处理链的其余部分(如果需要),通常通过将其再次转发到subsref或subsasgn.
如果您希望使用end关键字在另一个对象的下标表达式中,则必须有end方法定义。例如end多项式类的方法可能看起来像
function r = end (obj, index_pos, num_indices)
if (num_indices != 1)
error ("polynomial object may only have one index");
endif
r = length (obj.poly) - 1;
endfunction
这是一个相当通用的end具有类似于的行为的方法endOctave Array类的关键字。使用多项式类的一个例子是
p = polynomial ([1,2,3,4]);
p{end-1}
⇒ 3
对象本身也可以用作下标表达式中的索引,这从subsindex作用
idx = subsindex (obj) ¶将对象转换为索引向量。
当obj是用类构造函数定义的类对象,则subsindex是重载方法,它允许将此类对象转换为有效的索引向量。需要注意的是subsindex必须返回类的从零开始的实整数向量"double"。例如,如果类构造函数是
function obj = myclass (a)
obj = class (struct ("a", a), "myclass");
endfunction
然后subsindex作用
function idx = subsindex (obj) idx = double (obj.a) - 1.0; endfunction
可以如下使用
a = myclass (1:4); b = 1:10; b(a) ⇒ 1 2 3 4
最后,通过提供colon方法
r = colon (base, limit) ¶r = colon (base, increment, limit) ¶返回对应于的冒号表达式的结果base,limit,并且可选地,increment.
此函数等效于运算符语法base : limit 或base : increment : limit .
详见: linspace.
版权所有 © 2024-2025 Octave中文网
ICP备案/许可证号:黑ICP备2024030411号-2