Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab's arrayfun for uniform output of class objects

Tags:

oop

class

matlab

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

But get an error:

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

I can build it alternatively in a loop:

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

but what is wrong with this usage of arrayfun?

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.

like image 490
Serg Avatar asked Nov 29 '25 02:11

Serg


1 Answers

Perhaps the easiest is to use cellfun, or force arrayfun to return a cell array by setting the 'UniformOutput' option. Then you can convert this cell array to an array of obects (same as using cat above).

s = arrayfun(@(x) ID(x), ids, 'UniformOutput', false);
s = [s{:}];
like image 131
robince Avatar answered Nov 30 '25 20:11

robince



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!