How to record the first value every time it occurs?

6 views (last 30 days)
I cant figure out how to record n when the value in the matrix dist is first greater than 10 in each column. I should end up with 50 values for my out_of_bounds variable but I currently end up with only one for the first column of dist.
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(n) >= B & out_of_bounds==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 =n ;
end
end

Answers (1)

Star Strider
Star Strider on 2 Mar 2015
I don’t completely understand what you want to do. If you want to loop through N particles for M iterations each, use two nested for loops, the outer for each particle and the inner for the random walk of each particle.
Then:
B = 10;
for k1 = 1:N
count = 0;
for k2 = 1:M
... CODE ...
m(k1, k2) = ...
y(k1, k2) = ...
dist = hypot(m(k1,k2), y(k1,k2));
if dist <= B
count = count+1;
out_of_bounds(k1,k2) = count;
end
end
end
This is simply sketching out the code, but it may be the only way to do what you want. It isn’t possible to do all particles simultaneously, you have to iterate through each particle individually.
When the loop completes, I would also save all the variables of interest that it generated in a .mat file so you can use them again without having to re-run your code.
  4 Comments
Lilly Hoodenpyle
Lilly Hoodenpyle on 2 Mar 2015
What does the "..." mean in your version of the code?
Star Strider
Star Strider on 2 Mar 2015
The ‘...’ simply stands for code lines I didn’t want to type out. The ‘... CODE ...’ line stands for several lines of code. I’m sketching out the general idea of two nested loops.

Sign in to comment.

Categories

Find more on Creating and Concatenating Matrices 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!