フィルターのクリア

How to create classes in for loop?

7 ビュー (過去 30 日間)
Michael Simonovski
Michael Simonovski 2018 年 7 月 11 日
コメント済み: Steven Lord 2020 年 11 月 12 日
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 Center および File ExchangeConstruct 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