Help with trapz on a position graph

Hello, I'm doing homework for my class (first time with matlab), and I'm stuck. The first part of the question wanted us to plot the position of a particle using giving starting position and velocity (4 total inputs, x y position, x y velocity. It is supposed to be in a "box" so when it reaches y=0,1 or x=0,1 it should bounce off the wall, reversing velocity, and changing the position back into the box. I got this fine. It then wants us to calculate the total distance using trapz or quad. How would I do this? Thanks for the help. Here's the code:
%Calculates the motion (position and velocity) of a ball in a 1X1 box. Takes an x,y,vx, and vy values and calculates the new position and
%velocity. If the ball exceeds the boundary of the box, it will be moved
%back in
%Clear window and variables
clear
clc
%Declare variables
x=[-0.1 0.5 1.1]; %m (position)
y=[-0.1 0.5 1.1]; %m (position)
vx=1; %m/s (velocity)
vy=1; %m/s (velocity)
for k=1:length(x);
for s=1:length(y);
[ xNew, yNew, vxNew, vyNew ]= pos_vel_ball(x(k),y(s),vx,vy);
fprintf('The old position is (%0.2f , %0.2f) \n',x(k),y(s))
fprintf('The new position is (%0.3f , %0.3f) \n',xNew,yNew)
fprintf('The old velocity is (%0.2f , %0.2f) \n', vx,vy)
fprintf('The new velocity is (%0.3f , %0.3f) \n',vxNew,vyNew)
end
end
%Asks user for x,y,vx,vy and calculates a new positio and velocit from the
%given variables (problem 4)
x_asked=input('Give me x ');
y_asked=input('Give me y ');
vx_asked=input('Give me x velocity ');
vy_asked=input('Give me y velocity ');
v=sqrt(vxNew.^2+vyNew.^2);
xs=[];
ys=[];
while v >= 0.0001
axis( [-0.1 1.1 -0.1 1.1])
axis equal
[ xNew, yNew, vxNew, vyNew ]= pos_vel_ball( x_asked,y_asked,vx_asked,vy_asked);
x_asked=xNew;
y_asked=yNew;
vx_asked=vxNew;
vy_asked=vyNew;
xs=[xs xNew];
ys=[ys yNew];
plot(xNew,yNew);
hold on
v=sqrt(vxNew.^2+vyNew.^2);
grid on
end
Here's the function I called:
function [ xNew, yNew, vxNew, vyNew ] = pos_vel_ball( x, y, vx, vy )
%Calculate the position and velocity of the ball
h=0.05;
d=0.995;
vxNew = vx.*d;
vyNew = vy.*d;
xNew = x + vx.*h;
yNew = y + vy.*h;
for k=1:4 %check 4 times for each wall
if xNew<0
vxNew=-vxNew;
xNew=-xNew;
elseif xNew>1
vxNew=-vxNew;
dx=xNew-1;
xNew=1-dx;
elseif yNew<0
vyNew=-vyNew;
yNew=-yNew;
elseif yNew>1
vyNew=-vyNew;
dy=yNew-1;
yNew=1-dy;
end
end
end
And here's the actual problem/question, if that helps:
5) Start with your scripts/function from the bouncing ball problem of the previous. Modify them to use trapz (and optionally quad) to calculate the distance traveled given the user’s inputs. 6a) Brute force: Use the x and y values that you plotted last homework to directly calculate the distance traveled (distance is Δ

Risposte (0)

Richiesto:

il 17 Mag 2013

Community Treasure Hunt

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

Start Hunting!

Translated by