필터 지우기
필터 지우기

Adding fields and values to a structure iteratively

조회 수: 63 (최근 30일)
John Davis
John Davis 2020년 7월 17일
댓글: Stephen23 2020년 7월 18일
I wish to make a struct with n fields, each containing a probability distribution generated by makedist(). As an example, let's take n=3. My code looks like this:
prior(1)=makedist('uniform',-1,1);
prior(2)=makedist('uniform',-1,1);
prior(3)=makedist('uniform',-1,1);
priors=struct('prior1',prior(1),'prior2',prior(2),'prior3',prior(3));
I would like to build the struct "priors" iteratively in a loop when n is large, but I'm having lots of difficulty working with structs, even after reading the documentation and other questions posted here. Any advice would be much appreciated!
  댓글 수: 1
Stephen23
Stephen23 2020년 7월 18일
"I wish to make a struct with n fields,..."
Your code would be simpler and more efficient if you used a 1xn structure with one field:
S(1).prior = makedist('uniform',-1,1);
S(2).prior = makedist('uniform',-1,1);
S(3).prior = makedist('uniform',-1,1);

댓글을 달려면 로그인하십시오.

채택된 답변

Sindar
Sindar 2020년 7월 17일
n=3;
priors=struct();
for ind=1:n
priors.("prior"+ind) = makedist('uniform',-1,1);
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by