How to create a matrix of values from an if statement?
Show older comments
I have created a simulation of a predator carrying out a random walk in a 10x10 area, and when it encounters a stationary prey it stops. I want to create a histogram of i, which shows the distribution of how long it takes for the predator to encounter the prey. However, I cannot find a way to create a matrix containing the values of i. (The current output of histogram(i) is incorrect.)
I want to know how I can create a matrix of the values of i that are outputted from the if statement, so that I can create the histogram?
Here's my current code:
A = [randi(10), randi(10)]; %Random prey coordinates
m = 30; % number of predators being simulated
hold on;
for j = 1:m
n = 1000; % number of timesteps
x = zeros(1,n+1);
y = zeros(1,n+1);
x(1) = randi(10);
y(1) = randi(10);
for i = 2:n+1 %making the predator go up\down 1 each step
x(i) = x(i-1) + (randi(3)-2);
y(i) = y(i-1) + (randi(3)-2);
%Adding periodic boundary conditions
if x(i) == -1
x(i) = 10;
end
if x(i) == 11
x(i) = 0;
end
if y(i) == -1
y(i) = 10;
end
if y(i) == 11
y(i) = 0;
end
if [randi(10), randi(10)] == [x(i), y(i)] %if the path of the predator encounters the coordinates of the prey, end the loop and output i
i
break %ends this loop only
end
end
end
histogram(i)
Answers (1)
Jos (10584)
on 2 Feb 2018
The statement [randi(10), randi(10)] will change every time, moving the prey randomly around the field. Set the position of the prey before the loop in which you move the predator
preyX = randi(10)
Secondly you want to store te value of i when the predator hits the prey, so i can be used again for the next loop
if ...
result(j) = i ;
break % break out of inner loop
end
Pre-allacting the result before the outer loop is recommended:
result = zero(m,1);
After all simulations are done, use:
histogram (result)
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!