Writing a loop for structure array
조회 수: 3 (최근 30일)
이전 댓글 표시
Hello folks, I'm a newbie for matlab....got a seemingly easy question, I'd be really appreciated if someone can help.
So I wanna create structure array named "harvest".
Total sample number of "harvest" is 768, and each sample is subdivided into 4 categories(.shanghai/.fortune/.spinach/.lettuce).
The number in each cell is random integer between 0~10. However, under each category, the sum of that category has to <=4608.
The story behind is to simulate the 4 different vegetables' daily harvest for all the 768 households. Each vegetable's daily harvest cannot excess 4608.
I try to put in the code:
n=1:768;
harvest(n).shanghai=randi([0,10],1);
harvest(n).fortune=randi([0,10],1);
harvest(n).spinach=randi([0,10],1);
harvest(n).lettuce=randi([0,10],1);
sshanghai=sum(harvest(n).shanghai);
sfortune=sum(harvest(n).fortune);
sspinach=sum(harvest(n).spinach);
slettuce=sum(harvest(n).lettuce);
sshanghai,sfortune,sspinach,slettuce <= 4608
And it's not working....this is not a loop though...do you think I need to write a loop? And how to?
Many thanks!
댓글 수: 0
답변 (1개)
Walter Roberson
2015년 8월 9일
You can use structfun()
But first you need to define what should happen if the total would otherwise exceed 4608.
댓글 수: 2
Walter Roberson
2015년 8월 10일
while true
harv = randi([0 10], 768, 4);
if sum(harv(:)) <= 4608; break; end
end
Now write the values in harv into your structure.
참고 항목
카테고리
Help Center 및 File Exchange에서 Continuous Waveforms에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!