필터 지우기
필터 지우기

How to create new structure with each for loop?

조회 수: 33 (최근 30일)
Nicholas Kavouris
Nicholas Kavouris 2022년 4월 10일
댓글: Stephen23 2022년 4월 10일
I am trying to take a large dataset with mutlple fields and segment it and place it into unique structure with each for loop
if numel(start)==numel(stop)
for k=1:numel(start);
j=start(k):stop(k)+900;
field1="number"; value1=k;
field2='grill_state'; value2=grill_state(j) ;
field3='Set_Temp'; value3=SetTempF(j);
field4='TempF'; value4=Temp_F(j);
field5='AugerRPM'; value5=Auger_RPM(j);
strcat('Cook',num2str(k))=struct(field1,value1,field2,value2,field3,value3,field4,value4,field5,value5);
end
end
The goal is to take all values indexed between start and stop and place them into a structure titled Cookn for 1-n number of cooks.
so if there are 5 start points then loop should return struct cook1-cook5. Where am i going wrong?
  댓글 수: 1
Stephen23
Stephen23 2022년 4월 10일
"Where am i going wrong?"
You are trying to force numbers into variable names.
Doing so is possible, but only if you want to write slow, complex, inefficient, buggy code:
The neat, simple, and very efficient MATLAB approach is to use indexing, just as Matt J shows.

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

채택된 답변

Matt J
Matt J 2022년 4월 10일
if numel(start)==numel(stop)
N=numel(start);
clear Cook
for k=N:-1:1
j=start(k):stop(k)+900;
Cook(k).number=k;
Cook(k).grill_state=grill_state(j) ;
Cook(k).Set_Temp=SetTempF(j);
Cook(k).TempF=Temp_F(j);
Cook(k).AugerRPM=Auger_RPM(j);
end
end
  댓글 수: 2
Nicholas Kavouris
Nicholas Kavouris 2022년 4월 10일
thank you, much simpler. Any reason for backwards loop?
Matt J
Matt J 2022년 4월 10일
You're quite welcome, but please Accept-click the answer if it resolved your question.
The backward loop forces Matlab to create the Nth structure array element first. As a result, it forces the entire structure array to be pre-allocated after the first iteration of the loop.

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by