问题描述
我需要使用arrayfun建立类 ID
的对象数组:
I need to build an array of objects of class ID
using 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的用法有什么问题?
but what is wrong with this usage of arrayfun?
编辑(问题的澄清):问题不是如何解决问题(有几个解决方案),但为什么简单的语法 s = arrayfun(@ id)ID(id),ids);
不工作。谢谢。
Edit (clarification of the question): The question is not how to workaround the problem (there are several solutions), but why the simple syntax s = arrayfun(@(id) ID(id), ids);
doesn't work. Thanks.
推荐答案
您要求 arrayfun
t。
:
The output from arrayfun
must be:
对象不计为任何标量类型,这就是为什么解决方法都涉及使用单元格阵列作为输出。有一件事要尝试使用 cell2mat
将输出转换为所需的形式;它可以在一行中完成。 (我没有测试它。)
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));
这篇关于Matlab的arrayfun用于类对象的统一输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!