# How can I fix random numbers in a for loop?

5 views (last 30 days)
Andrew Burley on 14 Oct 2021
Commented: Andrew Burley on 15 Oct 2021
Hello everyone. I am trying to write a code that does something like this:
for k=1:10
j=0
for t=1:.1:10
j=j+1;
s1(j)=randi([1,5],1,1)*sin(1*t)+randi([1,5],1,1)*sin(2*t);
s2(j)=randi([1,5],1,1)*sin(1*t)+randi([1,5],1,1)*sin(2*t);
end
diff(k)=(s1-s2);
end
avgdiff=mean(diff)
but I want to fix the random integer for the entire loop of k. So each time, 1-10, that k is looped, a new random coefficient is generated for each polynomial. As it stands now, it seems like a new random coefficient is generated for each loop of t. I would prefer if it would be generated for each loop of k, such that, for example
diff(1)=[(3*sin(1*t)+2*sin(2*t))-(4*sin(1*t)+2*sin(2*t))]
diff(2)=[(1*sin(1*t)+3*sin(2*t))-(5*sin(1*t)+4*sin(2*t))]
I hope that makes sense. I am still trying to learn, so any feedback is appreciated. Thank you in advance!

David Hill on 14 Oct 2021
t=1:.1:10;
for k=1:10
s1=randi(5)*sin(1*t)+randi(5)*sin(2*t);
s2=randi(5)*sin(1*t)+randi(5)*sin(2*t);
Diff(k)=(s1-s2);
end
avgdiff=mean(Diff);
Andrew Burley on 15 Oct 2021
Thanks!

R2021b

### Community Treasure Hunt

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

Start Hunting!