- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
Mathworks File Exchange 存储库中有一些哈希或字典类的实现。我看过的所有内容都使用括号重载来进行键引用,例如
d = Dict;
d('foo') = 'bar';
y = d('foo');
这似乎是一个合理的接口(interface)。但是,如果您想轻松拥有包含其他词典的词典,最好使用大括号 {}
而不是圆括号,因为这可以让您绕过 MATLAB 的(似乎是任意的)语法不允许使用多个括号但允许使用多个大括号的限制,即
t{1}{2}{3} % is legal MATLAB
t(1)(2)(3) % is not legal MATLAB
所以如果你想轻松地在字典中嵌套字典,
dict{'key1'}{'key2'}{'key3'}
as 是 Perl 中的一个常见习语,并且在包括 Python 在内的其他语言中可能并且经常有用,那么除非你想使用 n-1
中间变量来提取字典条目 n
layers deep,这似乎是个不错的选择。重写该类的 subsref
和 subsasgn
操作以对 {}
执行与之前对 相同的操作似乎很容易()
,一切正常。
除了我尝试时没有。
这是我的代码。 (我已将其简化为最小情况。这里没有实现实际的字典,每个对象都有一个键和一个值,但这足以说明问题。)
classdef TestBraces < handle
properties
% not a full hash table implementation, obviously
key
value
end
methods(Access = public)
function val = subsref(obj, ref)
% Re-implement dot referencing for methods.
if strcmp(ref(1).type, '.')
% User trying to access a method
% Methods access
if ismember(ref(1).subs, methods(obj))
if length(ref) > 1
% Call with args
val = obj.(ref(1).subs)(ref(2).subs{:});
else
% No args
val = obj.(ref.subs);
end
return;
end
% User trying to access something else.
error(['Reference to non-existant property or method ''' ref.subs '''']);
end
switch ref.type
case '()'
error('() indexing not supported.');
case '{}'
theKey = ref.subs{1};
if isequal(obj.key, theKey)
val = obj.value;
else
error('key %s not found', theKey);
end
otherwise
error('Should never happen')
end
end
function obj = subsasgn(obj, ref, value)
%Dict/SUBSASGN Subscript assignment for Dict objects.
%
% See also: Dict
%
if ~strcmp(ref.type,'{}')
error('() and dot indexing for assignment not supported.');
end
% Vectorized calls not supported
if length(ref.subs) > 1
error('Dict only supports storing key/value pairs one at a time.');
end
theKey = ref.subs{1};
obj.key = theKey;
obj.value = value;
end % subsasgn
end
end
使用这段代码,我可以按预期分配:
t = TestBraces;
t{'foo'} = 'bar'
(很明显,t
的默认显示输出中的赋值工作。)所以 subsasgn
似乎可以正常工作。
但我无法检索值(subsref
不起作用):
t{'foo'}
??? Error using ==> subsref
Too many output arguments.
错误消息对我来说毫无意义,并且我的 subsref
处理程序的第一个可执行行处的断点从未命中,所以至少从表面上看这看起来像是 MATLAB 问题,而不是程序中的错误我的代码。
显然 ()
括号下标的字符串参数 是 是允许的,因为如果您将代码更改为使用 ()
就可以正常工作{}
。 (除非你不能嵌套下标操作,这是练习的对象。)
无论是洞察我在我的代码中做错了什么,任何使我正在做的事情不可行的限制,或者嵌套字典的替代实现,我们都将不胜感激。
最佳答案
简答,将此方法添加到您的类中:
function n = numel(obj, varargin)
n = 1;
end
编辑:长答案。
尽管 subsref
的函数签名出现在文档中的方式,它实际上是一个 varargout 函数 - 它可以产生可变数量的输出参数。大括号和点索引都可以产生多个输出,如下所示:
>> c = {1,2,3,4,5};
>> [a,b,c] = c{[1 3 5]}
a =
1
b =
3
c =
5
subsref
预期的输出数量取决于索引数组的大小。在本例中,索引数组的大小为 3,因此有三个输出。
现在,再看看:
t{'foo'}
索引数组的大小是多少?另外 3. MATLAB 不关心您打算将其解释为字符串而不是数组。它只看到输入大小为 3,而您的 subsref 一次只能输出 1 个东西。因此,参数不匹配。幸运的是,我们可以通过重载 numel
改变 MATLAB 确定预期输出数量的方式来纠正问题。 .引用自文档链接:
It is important to note the significance of numel with regards to the overloaded subsref and subsasgn functions. In the case of the overloaded subsref function for brace and dot indexing (as described in the last paragraph), numel is used to compute the number of expected outputs (nargout) returned from subsref. For the overloaded subsasgn function, numel is used to compute the number of expected inputs (nargin) to be assigned using subsasgn. The nargin value for the overloaded subsasgn function is the value returned by numel plus 2 (one for the variable being assigned to, and one for the structure array of subscripts).
As a class designer, you must ensure that the value of n returned by the built-in numel function is consistent with the class design for that object. If n is different from either the nargout for the overloaded subsref function or the nargin for the overloaded subsasgn function, then you need to overload numel to return a value of n that is consistent with the class' subsref and subsasgn functions. Otherwise, MATLAB produces errors when calling these functions.
就是这样。
关于oop - matlab subsref : {} with string argument fails, 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8713730/
如果您想使用 String.Concat() 连接 5 个或更多字符串,则它会使用 Concat(String[])。 为什么不一直使用 Concat(String[]) 而不再需要 Concat(S
今天在使用 String 时,我遇到了一种我以前不知道的行为。我无法理解内部发生的事情。 public String returnVal(){ return "5";
似乎在我所看到的任何地方,都有一些过时的版本,这些版本不再起作用。 我的问题似乎很简单。我有一个Java类,它映射到derby数据库。我正在使用注释,并且已经成功地在数据库中创建了所有其他表,但是在这
一、string::size_type() 在C++标准库类型 string ,在调用size函数求解string 对象时,返回值为size_type类型,一种类似于unsigned类型的int 数据
我正在尝试将数据保存到我的 plist 文件中,其中包含字符串数组的定义。我的plist - enter image description here 我将数据写入 plist 的代码是 -- let
我有一个带有键/值对的 JavaScript 对象,其中值是字符串数组: var errors = { "Message": ["Error #1", "Error #2"], "Em
例如,为了使用相同的函数迭代 List 和 List> ,我可以编写如下内容: import java.util.*; public class Test{ public static voi
第一个Dictionary就像 Dictionary ParentDict = new Dictionary(); ParentDict.Add("A_1", "1")
这是我的 jsp 文件: 我遇到了错误 The method replace(String, String, String) in the type Functions is not appl
我需要一些帮助。我有一个方法应该输出一个包含列表内容的 txt 文件(每行中的每个项目)。列表项是字符串数组。问题是,当我调用 string.Join 时,它返回文字字符串 "System.Strin
一位同事告诉我,使用以下方法: string url = "SomeURL"; string ext = "SomeExt"; string sub = "SomeSub"; string s
给定类: public class CategoryValuePair { String category; String value; } 还有一个方法: public
我正在尝试合并 Stream>>对象与所有 Streams 中的键一起映射到单个映射中. 例如, final Map someObject; final List>> list = someObjec
在这里使用 IDictionary 的值(value)是什么? 最佳答案 使用接口(interface)的值(value)始终相同:切换到另一个后端实现时,您不必更改客户端代码。 请考虑稍后分析您的代
我可以知道这两个字典声明之间的区别吗? var places = [String: String]() var places = [Dictionary()] 为什么当我尝试以这种方式附加声明时,只有
在 .NET 4.0 及更高版本中存在 string.IsNullOrWhiteSpace(string) 时,在检查字符串时使用 string.IsNullOrEmpty(string) 是否被视为
这个名字背后的原因是什么? SS64在 PowerShell 中解释此处的字符串如下: A here string is a single-quoted or double-quoted string
我打算离开 this 文章,尝试编写一个接受字符串和 &str 的函数,但我遇到了问题。我有以下功能: pub fn new(t_num: S) -> BigNum where S: Into {
我有一个结构为 [String: [String: String]] 的多维数组。我可以使用 for 循环到达 [String: String] 位,但我不知道如何访问主键(这个位 [String:
我正在尝试使用 sarama(管理员模式)创建主题。没有 ConfigEntries 工作正常。但我需要定义一些配置。 我设置了主题配置(这里发生了错误): tConfigs := map[s
我是一名优秀的程序员,十分优秀!