I thought that end might be a special form, like :, that can be special-cased in indexing operations, so I created a class to detect thisclassdef IndexDisplayer methods function subsref(self, s) disp(s); end endend您可以在以下示例中看到 : 的特殊情况You can see how : is special cased in the following example>> a = IndexDisplayer;>> a(1:3) type: '()' subs: {[1 2 3]}>> a(:) type: '()' subs: {':'}但是,当我用 end 索引时,我只看到However, when I index with end I just see>> a(end) type: '()' subs: {[1]}这里的 end 被替换为 1.1 从哪里来?我的第一个猜测是索引表达式 x(end) 中的任何 end 都将被替换为对 length(x) 的调用,所以我尝试覆盖 length 以及Here the end is replaced with a 1. Where does that 1 come from? My first guess was that any end inside an indexing expression x(end) would be replaced with a call to length(x) so I tried overriding length as wellclassdef IndexDisplayer methods function subsref(self, s) disp(s); end function len = length(self) len = 10; end endend然而,这给了>> a = IndexDisplayer;>> length(a)ans = 10>> a(end) type: '()' subs: {[1]}所以这个理论是窗外的.谁能解释一下end的语义?so that theory is out the window. Can anyone explain the semantics of end?推荐答案首先,我认为您的语法 x(1:min(5, end)) 完全有效.当我在 MathWorks 时,我记得有人指出了这一点,很多开发人员不得不花一些时间弄清楚发生了什么.我不确定他们是否真的同意这是否有问题.Firstly, I think it's kind of a bug, or at least an unexpected feature, that your syntax x(1:min(5, end)) works at all. When I was at MathWorks, I remember someone pointing this out, and quite a few of the developers had to spend a while figuring out what was going on. I'm not sure if they ever really agreed whether it was a problem or not.解释end的(预期)语义:end被实现为一个函数ind = end(obj, k, n).k 是包含end 的表达式的索引,n 是表达式中索引的总数.To explain the (intended) semantics of end: end is implemented as a function ind = end(obj, k, n). k is the index of the expression containing end, and n is the total number of indices in the expression.因此,例如,当您调用 a(1,end,1) 时,k 为 2,因为 end 在参数 2,并且 n 是 3,因为有 3 个参数.So, for example, when you call a(1,end,1), k is 2, as the end is in argument 2, and n is 3 as there are 3 arguments.ind 返回作为可以替换表达式中end 的索引.ind is returned as the index that can replace end in the expression.你可以为你自己的类重载end(就像你可以重载colon、size、subsref 等).You can overload end for your own classes (in the same way as you can overload colon, size, subsref etc).扩展您的示例:classdef IndexDisplayer methods function ind = end(self,k,n) disp(k) disp(n) ind = builtin('end', self, k, n); end endend>> a = IndexDisplayer;>> a(1,end,1) 2 3请参阅此处了解更多信息. 这篇关于Matlab 中“结束"的语义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-19 13:55