Filter löschen
Filter löschen

How to create classes in for loop?

7 Ansichten (letzte 30 Tage)
Michael Simonovski
Michael Simonovski am 11 Jul. 2018
Kommentiert: Steven Lord am 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!

Antworten (1)

James Tursa
James Tursa am 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 Kommentare
Matthew Osborne
Matthew Osborne am 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 am 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.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Construct and Work with Object Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by