How to initialize object array with different parameters?
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Daniel Glazar
il 21 Mar 2019
Commentato: Tristan Spiteri
il 11 Mar 2020
This is the sort of thing I want to do:
Define class:
classdef Class
properties
prop
end
methods
function obj = Class(param)
if nargin
obj.prop = param;
end
end
end
end
Then initialize object array like so:
dim = {3,2};
param = 1:6;
obj_arr(dim{:}) = Class(param)
and get and object array like so:
obj_arr =
2x3 Class array with properties:
prop
obj_arr(1,1).prop =
1
obj_arr(2,1).prop =
2
...
obj_arr(3,2).prop =
6
I have one idea that involves using a static method, but I'm having trouble implementing it, and it feels messy to me.
Also, I know that initalizing the object array like that doesn't work. I guess the idea of initializing an object array is to not pass any parameters and have all of them as clones of one another?
The whole reason for asking this question is because right now I'm doing the preallocation, then using a for loop to intiatiate each object (patient), which takes a lot of time, since I've implemented a particle swarm optimization for each object (patient). I want to be able to have the particle swarm optimization run for all the objects (patients) in the cohort at the same time.
Also, I've tried parfor, and it doesn't help any. I have 27 objects (patients) in my cohort.
0 Commenti
Risposta accettata
Guillaume
il 21 Mar 2019
With the current interface, this is probably the best you can do:
dim = [3,2];
param = 1:6;
param = num2cell(param); %each object param must be an element of a cell array
obj_arr(prod(dim)) = Class; %initialise all empty
obj_arr = reshape(obj_arr, dim); %reshape into desired shape
[obj_arr.prop] = param{:}; %deal each parameter to each object
If you use the same interface as the struct function where if the input is a cell array, the output is a structure array, then you could have this:
classdef Class %what a dangerous name! Too close to the all useful: class
properties
prop
end
methods
function obj = Class(param)
if nargin
if iscell(param)
[obj(1:numel(param)).prop] = param{:};
else
obj.prop = param;
end
end
end
end
end
%usage:
param = num2cell(1:6);
obj_arr = Class(param) %create a 1x6 array
celldisp({obj.arr}) %verify that each object got a single param.
4 Commenti
Tristan Spiteri
il 11 Mar 2020
lets say my class had 2 properties, how could I go about doing something similar.
I want an array of my object that are initialised with different paramaters for each property.
Sorry im very new to matlab, any help would be appreciated.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Data Type Identification in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!