Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays Matlab:按属性索引的对象数组_Arrays_Matlab_Object_Indexing_Properties - Fatal编程技术网

Arrays Matlab:按属性索引的对象数组

Arrays Matlab:按属性索引的对象数组,arrays,matlab,object,indexing,properties,Arrays,Matlab,Object,Indexing,Properties,在Matlab中,我想创建一个对象数组,从中我可以根据元素的一个独特属性提取元素,同时保持与普通索引相同的行为 下面是课堂: classdef myClass < dynamicprops properties Name = ''; Values end methods function obj = myClass(name,values) if nargin > 0

在Matlab中,我想创建一个对象数组,从中我可以根据元素的一个独特属性提取元素,同时保持与普通索引相同的行为

下面是课堂:

classdef myClass < dynamicprops

    properties
        Name = '';
        Values
    end

    methods
        function obj = myClass(name,values)
            if nargin > 0
                obj.Name = name;
                obj.Values = values;
            end
        end
    end
end
直接访问元素值的最简单方法是:

>> a(1).Values
ans =
 1     2     3     4     5     6     7     8     9    10
但我想通过名称而不是索引来调用数组元素,同时保持直接访问值的能力:

>> % /!\ This is intended behavior, not real result
>> a('two').Values(end-2:end) * 3
ans =
    54    57    60
我可以把两个=findobja,'Name','two';2.Valuesend-2:end*3,但这并不方便

我试着为我的对象设置一个自定义subsref方法,它工作得很好,但是我丢失了一些索引功能

我通过以下方法获得了预期的行为:

function out = subsref(obj,S)
    if strcmpi(S(1).type,'()') && ischar(S(1).subs{1})
        found = findobj(obj,'Name',S(1).subs{1});
        if ~numel(found)
            error(['Object with Name ''' S(1).subs{1} ''' not found.'])
        end
        if numel(S) == 1
            out = found(1);
        else
            out = builtin('subsref',found(1),S(2:end));
        end
    else
        out = builtin('subsref',obj,S);
    end
end
但是我不能用[a.values]或{a.Name}获取所有的名称/值。 Matlab返回:

Error using myClass/subsref
Too many output arguments.
我可能也会丢失其他索引功能

有更好的办法解决我的问题吗? 任何帮助都将不胜感激。

您可以在subsref中使用varargout来支持获取属性值的所有值的列表:

注意,我还向第一个if中的条件添加了~strcmpS1.subs{1},':',以支持:索引

我看到的另一个考虑事项是如何处理多个字符串:

a('one','two');
或混合类型:

a('one',3:end);
<>这是更多的拐角情况,但要考虑的事情。

a('one','two');
a('one',3:end);