How do I find out when a value first occurs?
Show older comments
My code is tracking a particle and its path, and I want to know how many 'steps' it takes to reach a distance greater than 10 from the origin. I have a matrix that I can look in and manually find out but I have an if statement that should find it for me but it's not working and I'm lost on how to make it work.
My code is:
close all; clear all; clc; format compact;
% m= particle
% dr = 1 %(delta)r = length of stride
% n = 1:1000 %n = number of steps
dr= 1;
%hold on %Allow for multiple graphs to be drawn
%Zeroes function is an empty vector that stores data
m=zeros(1000,50);
y=zeros(1000,50);
out_of_bounds=zeros(1,50); %since there is only 1 row it should only
%record the fist time it crosses the boundary
dist=zeros(1000,50);
for n = 2:50000; %1000 steps, 50 runs
a = 360 * rand; % random angle in [0,360]
%Each step taken at random from last position
m(n) = m(n-1) + dr * cosd(a);
y(n) = y(n-1) + dr * sind(a);
m(1,2:50) = 0; %Each particle starts at 0,0
y(1,2:50) = 0;
dist(n)=sqrt(((m(n)).^2)+((y(n)).^2)); %r is the radius equation
B=10; %Boundary is 10
if dist>= B && out_of_bounds(m)==0 %when the particle is greater than the distance of 10
%then it should somehow record the number of steps into the out of
%bounds array
out_of_bounds(m)=n;
end
end
Answers (2)
Star Strider
on 2 Mar 2015
You need to subscript ‘m’ both times in your if statement and change the && to &.
This works:
dr= 1;
%hold on %Allow for multiple graphs to be drawn
%Zeroes function is an empty vector that stores data
m=zeros(1000,50);
y=zeros(1000,50);
out_of_bounds=zeros(1,50); %since there is only 1 row it should only
%record the fist time it crosses the boundary
dist=zeros(1000,50);
for n = 2:50000; %1000 steps, 50 runs
a = 360 * rand; % random angle in [0,360]
%Each step taken at random from last position
m(n) = m(n-1) + dr * cosd(a);
y(n) = y(n-1) + dr * sind(a);
m(1,2:50) = 0; %Each particle starts at 0,0
y(1,2:50) = 0;
dist(n)=sqrt(((m(n)).^2)+((y(n)).^2)); %r is the radius equation
B=10; %Boundary is 10
if dist>= B & out_of_bounds(m(n))==0 %when the particle is greater than the distance of 10
%then it should somehow record the number of steps into the out of
%bounds array
out_of_bounds(m(n))=n;
end
end
figure(1)
plot(m, y)
grid
I leave it to you to determine if it produces the correct output.
The plot is optional. I added it because I wanted to see what your result looked like.
11 Comments
Kathryn Jordan
on 2 Mar 2015
Star Strider
on 2 Mar 2015
My pleasure.
What isn’t yet solved?
Kathryn Jordan
on 2 Mar 2015
Star Strider
on 2 Mar 2015
Edited: Star Strider
on 2 Mar 2015
This was absolutely obvious but I didn’t see it before! (Chalk it up to a long day.)
Change your if statement to subscript ‘dist’:
if dist(n) >= B
I won't get into the full details, but it otherwise considered ‘dist’ as a vector. If you don’t tell your statement what element to test, it tests only the first element in the vector. There are ways around that, but you need to test only the current element, so subscripting it works in your code.
You might also consider changing your ‘out_of_bounds’ assignment to:
out_of_bounds=n;
but since I don’t know how you want to track it, I’ll leave to you to decide what you want to put into it.
Kathryn Jordan
on 2 Mar 2015
Edited: Kathryn Jordan
on 2 Mar 2015
Star Strider
on 2 Mar 2015
Edited: Star Strider
on 2 Mar 2015
Change the ‘out_of_bounds’ assignment to:
out_of_bounds(n)=n;
That should work.
Or, you can create a separate counter (for instance, ‘k’) for ‘out_of_bounds’, intitialise it to 0 before the loop, and just increment it before the assignment. That would change your code inside your if block to:
k = k + 1;
out_of_bounds(k)=n;
Kathryn Jordan
on 2 Mar 2015
Edited: Kathryn Jordan
on 2 Mar 2015
Star Strider
on 2 Mar 2015
Edited: Star Strider
on 2 Mar 2015
Try the full revised code:
dr= 1;
%hold on %Allow for multiple graphs to be drawn
%Zeroes function is an empty vector that stores data
m=zeros(1000,50);
y=zeros(1000,50);
out_of_bounds=zeros(1,50); %since there is only 1 row it should only
%record the fist time it crosses the boundary
dist=zeros(1000,50);
for n = 2:50000; %1000 steps, 50 runs
a = 360 * rand; % random angle in [0,360]
%Each step taken at random from last position
m(n) = m(n-1) + dr * cosd(a);
y(n) = y(n-1) + dr * sind(a);
m(1,2:50) = 0; %Each particle starts at 0,0
y(1,2:50) = 0;
dist(n)=sqrt(((m(n)).^2)+((y(n)).^2)); %r is the radius equation
B=10; %Boundary is 10
if dist(n)>= B %when the particle is greater than the distance of 10
%then it should somehow record the number of steps into the out of
%bounds array
out_of_bounds(n)=n;
end
end
idx_oob = find(out_of_bounds > 0);
Be sure to look at ‘idx_oob’.
Kathryn Jordan
on 2 Mar 2015
Star Strider
on 2 Mar 2015
I have to admit I’m having a difficult time understanding what you’re doing.
How many times are you iterating for each particle?
How many particles do you have?
I’m beginning to think it might be best to set up two nested loops, the outer one iterating over the particles and the inner one iterating each particle in turn. I doubt you can do all of them at once and get any useful information.
Image Analyst
on 2 Mar 2015
I think so. That's exactly what I was working on when you were posting this. I've posted my code.
Image Analyst
on 2 Mar 2015
Edited: Image Analyst
on 2 Mar 2015
Try this code. I think it's what you want to do but it's more robust and general.
% Monte Carlo experiment for random walk
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 20;
% radius = length of one step.
radius = 1;
% Define Monte Carlo parameters
numExperiments = 50;
maxSteps = 1000;
% Initialize data.
x = zeros(maxSteps, numExperiments);
y = zeros(maxSteps, numExperiments);
% Since there is only 1 row it should only
%record the fist time it crosses the boundary
out_of_bounds=zeros(1, numExperiments);
dist=zeros(maxSteps, numExperiments);
B = 10; % Boundary is 10 = max allowed distance before we go to next particle
for experiment = 1 : numExperiments
for stepNumber = 2: maxSteps
angle = 360 * rand; % random angle in [0,360]
% Find the location of the next point
x(stepNumber, experiment) = x(stepNumber-1, experiment) + radius * cosd(angle);
y(stepNumber, experiment) = y(stepNumber-1, experiment) + radius * sind(angle);
% Find distance from origin (0,0)
dist(stepNumber, experiment)=sqrt(x(stepNumber, experiment).^2 + y(stepNumber, experiment).^2);
if dist(stepNumber, experiment) >= B
% Then the particle is greater than the distance of 10
% Record the number of steps
% it took to get out of bounds.
out_of_bounds(experiment) = stepNumber;
% All other points will be whatever this distance is.
dist(stepNumber+1:end, experiment) = dist(stepNumber, experiment);
break; % Quit tracking this particle.
end
end
end
maxNumberOfSteps = max(out_of_bounds);
% Plot the number of steps to get out of bounds.
plot(out_of_bounds, 'b-', 'LineWidth', 2);
xlim([0, numExperiments]);
title('Steps until out of bounds', 'FontSize', fontSize);
xlabel('Experiment Number', 'FontSize', fontSize);
ylabel('Number of Steps Until Out of Bounds', 'FontSize', fontSize);
grid on;
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 1 1]);
% Give a name to the title bar.
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')
% Plot the distances as a function of step number.
figure
plot(dist, 'LineWidth', 2);
xlim([0, maxNumberOfSteps]);
grid on;
title('Distance vs. Step Number', 'FontSize', fontSize);
xlabel('Step Number', 'FontSize', fontSize);
ylabel('Distance', 'FontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 1 1]);
% Give a name to the title bar.
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')


Attached is the file, in case the formatting and line wrapping above is messed up.
I've also attached my earlier random walk code (not based on your code like this is). For extra bonus points, plot each path, take the histogram of distances and plot the distribution, and see how well your experiment matches up with the theoretical formula for distance vs. step.
Categories
Find more on Monte Carlo Analysis in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!