Creating a counter in matlab. - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

Creating a counter in matlab.

DgraymanDgrayman Posts: 4Member
Hello. what im trying to do is create a random walk simulation 1000 times where i am tracking the movement of an object in 48 steps. i figured out what i need to do, but the last thing im trying to do is to count how many times the walk ends at a number where y>12. So for example if the walk ends at y=13, it adds 1 to the counter, but if it ends on y=8, it will not add 1 to the counter.
The reason im doing this is so i can find a percentage of how many times the object ends at y>12 which i want to do by finding 'number of times object went over twelve divided by 1000
(ans=counter/1000). heres my code:

>> %n= # of fungus sources
>> %t= # of time steps (inch)
>> %N= # of simulation runs
>> %alfa= random variables for angle
>> %d= random variable for distance
>> %M1= x coordinate of a point
>> %M2= y coordinate at a point
>> %maxy= max y value at each step
>> %count= counter that stores # of times maxy is > 12 inches
>> n=1;
>> t=48;
>> N=1000;
>> count=0;
>> for n=1:N;
for i=1:t;
if m2(i+1,1:n)<0;

>> if maxy>12
>> ans=count/N

ans =

Looking at my workspace i see there are times when y>12 but my counter is not recording it, so i keep getting an answer of 0. Any suggestions on how to get my counter working? Much appreciated.


  • giuggiug Posts: 217Member
    You have to index maxy, something like this:
    then out of the for loop
    finds the positions of the elements >12
    finds the values of the elements >12
  • DgraymanDgrayman Posts: 4Member
    as soon as i replace the line to 'maxy(n)=max(maxy(n-1),m2(i+1,1:n))' it gives me this error:'??? Attempted to access maxy(0); index
    must be a positive integer or logical.'
  • giuggiug Posts: 217Member
    Yes, you have to shift the indices. Because when n=1, n-1=0 and maxy(0) doesn't exist.
Sign In or Register to comment.