Writing a loop for structure array
3 views (last 30 days)
Show older comments
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 Comments
Answers (1)
Walter Roberson
on 9 Aug 2015
You can use structfun()
But first you need to define what should happen if the total would otherwise exceed 4608.
2 Comments
Walter Roberson
on 10 Aug 2015
while true
harv = randi([0 10], 768, 4);
if sum(harv(:)) <= 4608; break; end
end
Now write the values in harv into your structure.
See Also
Categories
Find more on Continuous Waveforms in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!