For-Loop: Iterations using non-integer indices

14 vues (au cours des 30 derniers jours)
John McCall
John McCall le 26 Avr 2017
Modifié(e) : KSSV le 26 Avr 2017
I am creating a function to solve for Projectile Motion using Quadratic Drag... I am new to MATLAB and have written a function for Quadratic Drag that yields Vdotx (acceleration in x-direction) and Vdoty (acceleration in y-direction) both varying with time. I need to write a for loop to evaluate velocity in both directions using:
%Vx(t+dt)= Vx(t)+Vdotx(t)dt
%Vy(t+dt)= Vy(t)+Vdoty(t)dt
And then solving for position using:
%x(t+dt) = x(t)+Vx(t)dt
%y(x+dt) = y(t)+Vy(t)dt
The issue I can't get around is when using "For loops" a real positive integer is needed for indices. For example I would like my for loop to evaluate the x and y positions for a dt of 0.001. To do this I have written:
dt = 0.001;
Vo = 10;
theta = (pi/180)*33.3;
Vox = Vo*cos(theta);
Voy = Vo*sin(theta);
Vx(1) = Vox;
Vy(1) = Voy;
y(1) = 10;
x(1) = 0;
for t = 1:dt:8
Vx(t+dt)=Vx(t)+Vdotx*dt;
Vy(t+dt)=Vx(t)+Vdotx*dt;
x(t+dt) = x(t)+Vx(t)*dt
y(t+dt) = x(t)+Vy(t)*dt
end
This does not work because the indice (dt) is not an integer. Please help.
Thank you

Réponse acceptée

KSSV
KSSV le 26 Avr 2017
Modifié(e) : KSSV le 26 Avr 2017
You should follow like this:
dt = 0.001;
Vo = 10;
theta = (pi/180)*33.3;
Vox = Vo*cos(theta);
Voy = Vo*sin(theta);
t = 1:dt:8 ;
nt = length(t) ;
Vx = zeros(1,nt) ;
Vy = zeros(1,nt) ;
x = zeros(1,nt) ;
y = zeros(1,nt) ;
Vx(1) = Vox;
Vy(1) = Voy;
y(1) = 10;
x(1) = 0;
Vdotx = rand ; % not defined so I have taken random value
for i = 2:length(t)
Vx(i)= Vx(i-1)+Vdotx*dt;
Vy(i)=Vx(i-1)+Vdotx*dt;
x(i) = x(i-1)+Vx(i)*dt ;
y(i) = x(i-1)+Vy(i)*dt ;
end

Plus de réponses (1)

Walter Roberson
Walter Roberson le 26 Avr 2017
tvals = 0:dt:8;
nt = length(tvals) ;
x = zeros(1, nt)
y = zeros(1, nt)
for tidx = 1 : nt
t = tvals(tidx)
x(tidx+1) = x(tidx) +.....
end

Catégories

En savoir plus sur MATLAB dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by