Reputation: 33
function [N] = rand_walk1(n)
j = zeros(1,n); %j will be the output vector
i=2;
for i= 2:n %This 'for' loop will randomly add or subtract 1 to each entry of the vector j, starting from j(2).
if rand >= 0.5 %This 'if' statement returns 1 or -1 with equal probability (it uses the uniform distribution with parameters [0,1]).
v = 1;
elseif rand <0.5
v = -1;
end
j(i)=j(i-1)+v;
end
N = j;
end
This is my function, sometimes it works and some other times it returns the following error:
Error in rand_walk1 (line 10)
j(i)=j(i-1)+v;
Any ideas of why I'm randomly getting this error, while some other times the function works?
Upvotes: 0
Views: 39
Reputation: 16791
Occasionally, sometimes, v
is unassigned. Let's look at your random number generation:
if rand >= 0.5
v = 1;
elseif rand <0.5
v = -1;
end
The first if
sets v = 1
half of the time. The other half of the time, you want to set v = -1
. But what you're doing is creating a new random number and checking that. If that new random number is also less than 0.5
, you get a good result. If it's greater than 0.5
, you'll just fall through and v
will be unchanged. If this is your first time through the loop, there's nothing to change, so v
will remain unassigned. That's when you get an error.
Instead, you want to do this:
if rand >= 0.5
v = 1;
else
v = -1;
end
This way, if your result is < 0.5
, you set v = -1
every time. It's got to be one or the other. You don't have to check again.
I'd like to note that one of the reasons this bug was a bit trickier to find is that you called the function rand
without any parentheses after it. rand
could be mistaken for a variable name while rand()
is obviously a function call with no arguments. Not a big deal, and perfectly legal MATLAB, but every little bit helps when it comes to code clarity.
Upvotes: 3