Saving the last value of a loop that will run 100 times

I have a function x that is dependent on a random variable s, where s =randn(1,1) the function x=x+s , where x will be replaced by the new value everytime the loop runs i need to create a loop script that when x is less/equal to -10 or more/equal to 10, it will stop and calculate how many times the loop has ran. I then need to run this loop in a loop 100 times and calculate the average number of times the loop ran to hit the 10/-10 condition in a total of 100 times. My script looks like this with alot missing:
x=0;
step=0;
while (x<10)&&(x>-10)
s=randn(1,1);
x=x+s;
step=step+1
end

 Accepted Answer

step = zeros(100,1);
for k=1:100
x=0;
step_actual=0;
while (x<10)&&(x>-10)
step_actual = step_actual+1;
s=randn(1,1);
x=x+s;
end
step(k)=step_actual;
end
step_mean = mean(step);

More Answers (1)

x=0;
step=0;
X = zeros([],1) ;
while (x<10)&&(x>-10)
s=randn(1,1);
x=x+s;
step=step+1
X(step) = x ;
end
x is saved in X.

1 Comment

Hi thankyou! But is it possible for example, my first run on the loop returns me a final value of step=200 and 100 on my 2nd run. i want to store 200 and 100 in a matrix [200,100, the remaining values of 98 runs]. How do i do that?

Sign in to comment.

Categories

Find more on Loops and Conditional Statements 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!