How to create classes in for loop?

9 views (last 30 days)
Michael Simonovski
Michael Simonovski on 11 Jul 2018
Commented: Steven Lord on 12 Nov 2020
Hello
i would like to create objects in a for loop, where it get his number through an input of his number. In another for loop the object should be called with the help of the number and the properties should be set. How it can be done?
Thank you in advance!

Answers (1)

James Tursa
James Tursa on 11 Jul 2018
Just use a regular for loop with indexing. E.g.,
for k=1:n
x(k) = myclass(whatever initialization is appropriate goes here);
end
Then you can set properties downstream. E.g.,
x(1).prop1 = something;
x(2).prop2 = something_else;
etc.
  12 Comments
Matthew Osborne
Matthew Osborne on 12 Nov 2020
How can this be done for a gprfit class? For example, this is not possible:
for i = 1:10
gpr(i) = fitrgp(X,Xdot(:,i));
end
Thanks,
Steven Lord
Steven Lord on 12 Nov 2020
If the class in question doesn't allow users to store them in an array, put them in a cell array instead. For instance, you can't put function handles in an array but you can put them in a cell array instead.
c = cell(1, 3);
for k = 1:3
c{k} = @(x) x.^k;
end
c{3}(7) % 7^3 = 343
ans = 343
% this code WON'T work
a = @(x) x.^1;
a(2) = @(x) x.^2;
Nonscalar arrays of function handles are not allowed; use cell arrays instead.

Sign in to comment.

Categories

Find more on Construct and Work with Object Arrays in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!