필터 지우기
필터 지우기

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 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