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!