3

我需要ID使用arrayfun构建一个类对象数组:

% ID.m
classdef ID < handle
    properties
        id
    end
    methods
        function obj = ID(id)
            obj.id = id;
        end
    end
end

但是得到一个错误:

>> ids = 1:5;
>> s = arrayfun(@(id) ID(id), ids) 
??? Error using ==> arrayfun
ID output type is not currently implemented.

我可以在循环中交替构建它:

s = [];
for k = 1 : length(ids)
    s = cat(1, s, ID(ids(k)));
end

但是arrayfun的这种用法有什么问题?

编辑(澄清问题):问题不是如何解决问题(有几种解决方案),而是为什么简单的语法s = arrayfun(@(id) ID(id), ids);不起作用。谢谢。

4

3 回答 3

5

'UniformOutput'也许最简单的方法是使用 cellfun,或者通过设置选项强制 arrayfun 返回一个元胞数组。然后,您可以将此单元数组转换为对象数组(与上面使用 cat 相同)。

s = arrayfun(@(x) ID(x), ids, 'UniformOutput', false);
s = [s{:}];
于 2012-06-05T13:24:56.863 回答
3

You are asking arrayfun to do something it isn't built to do.

The output from arrayfun must be:

scalar values (numeric, logical, character, or structure) or cell arrays.

Objects don't count as any of the scalar types, which is why the "workarounds" all involve using a cell array as the output. One thing to try is using cell2mat to convert the output to your desired form; it can be done in one line. (I haven't tested it though.)

s = cell2mat(arrayfun(@(id) ID(id), ids,'UniformOutput',false));
于 2012-06-05T15:26:43.673 回答
2

这就是我创建对象数组的方式

s = ID.empty(0,5);
for i=5:-1:1
    s(i) = ID(i);
end

提供不带参数的“默认构造函数”总是一个好主意,或者至少使用默认值:

classdef ID < handle
    properties
        id
    end
    methods
        function obj = ID(id)
            if nargin<1, id = 0; end
            obj.id = id;
        end
    end
end
于 2012-06-05T22:34:19.827 回答