# SOLVED: Error while trying to repeat a script multiple times in a for loop

2 views (last 30 days)
Lauren Nixon on 26 Aug 2019
Edited: Lauren Nixon on 26 Aug 2019
Hi there,
I am trying to execute this code 500 times and save it as an array, x.
u=rand();
m=1;
while(u>=cum_prob(m))%
m=m+1;
end
x=(bin_edges(m-1)-bin_edges(m-2))/(cum_prob(m-1)-cum_prob(m-2))*(u-((((bin_edges(m-1)*cum_prob(m-2))-((bin_edges(m-2)*cum_prob(m-1))))/(bin_edges(m-1)-bin_edges(m-2)))));
That works when I run it. Now i need to do this 500 times and stores the results in an array, x. The code that I have written to do so is shown below, however I am getting the error "Array indices must be positive integers or logical values." at the line that starts with x(a)=.....
x=zeros(1,500);
for a=1:500
u=rand();
m=1;
while(u>=cum_prob(m))%
m=m+1;
end
x(a)=(bin_edges(m-1)-bin_edges(m-2))/(cum_prob(m-1)-cum_prob(m-2))*(u-((((bin_edges(m-1)*cum_prob(m-2))-((bin_edges(m-2)*cum_prob(m-1))))/(bin_edges(m-1)-bin_edges(m-2)))));
end
If anyone could please point me in the right direction, that would be great! Thankyou

#### 1 Comment

Alex Mcaulley on 26 Aug 2019
We don't have your variables cum_prob and bin_edges to see what is happening. But I guess that the problem is: What happens when m == 1 or m == 2?
cum_prob(-1) %or cum_prob(0) are not defined!

R2018b

### Community Treasure Hunt

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

Start Hunting!