How to create classes in for loop?

7 次查看(过去 30 天)
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!

回答(1 个)

James Tursa
James Tursa 2018-7-11
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 个评论
Matthew Osborne
Matthew Osborne 2020-11-12
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 2020-11-12
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Construct and Work with Object Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by