今天看到知乎上haitao的博客https://zhuanlan.zhihu.com/p/341374091, 想到关于MATLAB的这个索引方法会带来的一些好处,以及自己对链式语法的理解,写下这篇博客。
1. 关于函数返回值的属性的直接访问
在MATLAB里面,一般是不支持双括号的索引方式,比如我们需要提取魔方矩阵的第二行的元素
>> magic(3)(2,:)
Error: Indexing with parentheses '()' must appear as the last operation of a valid indexing
expression.
一般的做法是写两行就可以了
>> a = magic(3)
a =
8 1 6
3 5 7
4 9 2
>> b = a(2,:)
b =
3 5 7
那么是否存在一行代码可以实现这个功能的方式呢?答案是存在,以前的做法是这样的
>> feval(@(x)x(2,:), magic(3))
ans =
3 5 7
在MATLAB支持返回对象的属性的直接访问之后(见知乎链接),那么我们就可以构造table对象来操作了
>> table(magic(3)).(1)(2,:)
ans =
3 5 7
2.关于链式语法
大家都知道java的链式语言,即c.method1().method2().method3(),...
那么MATLAB是否支持呢,我下面写个简单示例
保存为A.m
classdef A<handle
methods
function z = add(obj,x,y)
z = x + y;
end
end
end
保存为B.m
classdef B<handle
methods
function z = add(obj)
z = A;
end
end
end
在command window下面执行操作
>> b = B
b =
B with no properties.
>> b.add().add(1,2)
ans =
3