MatLab Code for Baseball Not Working

In summary, the Homework Equations cannot be solved using the simple kinematics method proposed. The Attempt at a Solution provides a linear solution for the position and velocity, but the plot is incorrect.
  • #1
grandpa2390
474
14

Homework Statement


I am trying to create this plot in MatLab
?temp_hash=508bdd4a90a57a3982ca08ab7b90103b.png


I'm starting out doing the simplest one, no drag, no wind. simple kinematics, right? but I can not get my code to run.

Homework Equations


Kinematic Equations

The Attempt at a Solution



Code:
close all

clear all

clc
%%defining variables

tMin = 0 %seconds

angleWithHorizontal = 35 %degrees

initialVelocity = 100 * .44704 %converting mph to m/s

tailWind = 10 * .44704 %converting mph to m/s

headWind = 10 *.44704 %converting mph to m/s

gravity = -9.8 %m/s^2

dt = .1 %change in time

mass = 1%unknown

initialVelocityY = initialVelocity * sin(angleWithHorizontal)

initialVelocityX = initialVelocity * cos(angleWithHorizontal)

timeToMaxHeight = -initialVelocity / gravity

tMax = 2*timeToMaxHeight

initialPositionX = 0

initialPositionY = 0

accelerationX = 0

distanceTraveledX = initialPositionX + initialVelocityX * tMax + .5 * accelerationX * tMax^2%%Position in Space Without Drag nor Wind

t = tMin:dt:tMax; % time steps

[j,k] = size(t);

velocityWithoutDrag(1) = initialVelocityY;

positionX(1) = initialPositionX;

positionY(1) = initialPositionY;

% calculate instantenous speeds and position

for i = 2:k

velocityWithoutDrag(i) = velocityWithoutDrag(i-1) + (gravity*dt)

positionX(i) = positionX(i-1) + velocityWithoutDrag(i)*dt + .5*gravity*dt^2

positionY(i) = positionY(i-1) + velocityWithoutDrag(i)*dt + .5*gravity*dt^2

end%%Plots

figure(1)

hold on

box on

plot(positionX,positionY,'-k')

set(gca,'Xtick',linspace(0,150,4),'fontsize',18,'Ytick',linspace(0,30,4))

set(gcf,'Color','w');

set(gcf,'Resize','on');
hold off

whenever I try to plot, I get a linear line. and the graph doesn't even have the correct domain and range or increments. It is weird because I borrowed the code from a previous problem I did, and just changed a bit of it.

I'm certain the problem is probably with my matrices, but I am still new to this. At this point I am just tackling the baseball in a vacuum part of the plot.
 

Attachments

  • Screen Shot 2018-03-04 at 11.25.32 PM.png
    Screen Shot 2018-03-04 at 11.25.32 PM.png
    19.4 KB · Views: 820
  • ?temp_hash=508bdd4a90a57a3982ca08ab7b90103b.png
    ?temp_hash=508bdd4a90a57a3982ca08ab7b90103b.png
    19.4 KB · Views: 803
Last edited:
Physics news on Phys.org
  • #2
Your X and Y equations are essentially identical, so the plot will be linear. Gravity does not effect the X velocity (if that is horizontal).
 
  • #3
FactChecker said:
Your X and Y equations are essentially identical, so the plot will be linear. Gravity does not effect the Y velocity (if that is horizontal).

But they aren't identical. the acceleration in the X equation is 0 so that term is 0. the y equation has an acceleration of -9.8 so it should go up and then come back down.

What did I do wrongedit: I see what I did. I see what you are referring to. right variable in one part. wrong variable in another. for x
 
  • #4
grandpa2390 said:
But they aren't identical. the acceleration in the X equation is 0 so that term is 0. the y equation has an acceleration of -9.8 so it should go up and then come back down.

What did I do wrong
Regardless of how they start and the initial rates, the horizontal position and velocity (I guess the X values) should not be affected by gravity.

PS. I changed the horizontal from Y to X in my post #2.
 
  • #5
@FactChecker

Ok I corrected the typo in my look. the acceleration in the X position formula has been corrected. my plot is still incorrect though.

Matlab:
close all
clear all
clc

%%defining variables
tMin = 0 %seconds
angleWithHorizontal = 35 %degrees
initialVelocity = 100 * .44704 %converting mph to m/s
tailWind = 10 * .44704 %converting mph to m/s
headWind = 10 *.44704 %converting mph to m/s
gravity = -9.8 %m/s^2
dt = .1 %change in time
mass = 1%unknown
initialVelocityY = initialVelocity * sin(angleWithHorizontal)
initialVelocityX = initialVelocity * cos(angleWithHorizontal)
timeToMaxHeight = -initialVelocity / gravity
tMax = 2*timeToMaxHeight
initialPositionX = 0
initialPositionY = 0
accelerationX = 0
distanceTraveledX = initialPositionX + initialVelocityX * tMax + .5 * accelerationX * tMax^2

%%Position in Space Without Drag nor Wind
t = tMin:dt:tMax; % time steps
[j,k] = size(t);
velocityWithoutDrag(1) = initialVelocityY;
positionX(1) = initialPositionX;
positionY(1) = initialPositionY;

% calculate instantenous speeds and position
for i = 2:k
velocityWithoutDrag(i) = velocityWithoutDrag(i-1) + (gravity.*dt)
positionX(i) = positionX(i-1) + velocityWithoutDrag(i)*dt + .5*accelerationX.*dt.^2
positionY(i) = positionY(i-1) + velocityWithoutDrag(i)*dt + .5*gravity.*dt.^2
end%%Plots
figure(1)
hold on
box on
plot(positionX,positionY,'-k')
set(gca,'Xtick',linspace(0,150,4),'fontsize',18,'Ytick',linspace(0,30,4))
set(gcf,'Color','w');
set(gcf,'Resize','on');
hold off
 
Last edited by a moderator:
  • #6
FactChecker said:
Regardless of how they start and the initial rates, the horizontal position and velocity (I guess the X values) should not be affected by gravity.
that was a typo. I have a variable accelerationX that was supposed to be in the positionX formula. thanks for pointing it out. but the problem persists...

edit: I'm looking at my formula again, and using the same value for velocity in both equations. that isn't what I meant to do either. yikes!

let me rework this. and come back. thanks for your help!
 
  • #7
Be very careful and methodical about which positions and velocities you apply gravity to. Keep track of the X and Y values separately for position and velocity. I think that will make it work.
 
  • #8
FactChecker said:
Be very careful and methodical about which velocities and accelerations you apply gravity to. Keep track of the X and Y values separately for position and velocity. I think that will make it work.

yeah. you can see from the start of my code that I began by properly creating the components. but in trying to reuse code I don't completely understand that modeled a 1-D problem. I got so caught up and figuring out how to adapt the code properly, the physics got skewed.

I'm going to create two separate loops I think. Will probably need a different matrix for the 2 velocities.
edit: x velocity doesn't change. lol. overcomplicating things.
 
  • #9
@FactChecker

OK! Now we are making progress. I corrected my formulas, and the graph is parabolic the way it should be. but it is not showing the correct domain and range. it's like from something to 0 in both the domain and range. I don't get it.

Matlab:
close all
clear all
clc

%%defining variables
tMin = 0 %seconds
angleWithHorizontal = 35 %degrees
initialVelocity = 100 * .44704 %converting mph to m/s
tailWind = 10 * .44704 %converting mph to m/s
headWind = 10 *.44704 %converting mph to m/s
gravity = -9.8 %m/s^2
dt = .1 %change in time
mass = 1%unknown
initialVelocityY = initialVelocity * sin(angleWithHorizontal)
initialVelocityX = initialVelocity * cos(angleWithHorizontal)
timeToMaxHeight = -initialVelocity / gravity
tMax = 2*timeToMaxHeight
initialPositionX = 0
initialPositionY = 0
accelerationX = 0
distanceTraveledX = initialPositionX + initialVelocityX * tMax + .5 * accelerationX * tMax^2

%%Position in Space Without Drag nor Wind
t = tMin:dt:tMax; % time steps
[j,k] = size(t);
velocityWithoutDragY(1) = initialVelocityY;
positionX(1) = initialPositionX;
positionY(1) = initialPositionY;

% calculate instantenous speeds and position
for i = 2:k
velocityWithoutDragY(i) = velocityWithoutDragY(i-1) + (gravity.*dt)
positionX(i) = positionX(i-1) + initialVelocityX*dt + .5*accelerationX.*dt.^2
positionY(i) = positionY(i-1) + velocityWithoutDragY(i)*dt + .5*gravity.*dt.^2
end

%%Plots
figure(1)
hold on
box on
plot(positionX,positionY,'-k')
set(gca,'Xtick',linspace(0,150,4),'fontsize',18,'Ytick',linspace(0,30,4))
set(gcf,'Color','w');
set(gcf,'Resize','on');
hold off
 
Last edited by a moderator:
  • #10
The thing to do is to nurse it through step-by-step and see that each step calculates the values that make sense. Running the whole thing fills up the screen and all I can see is that all your X and Y values are negative and get more negative with time. That is wrong. Try one command at a time from the beginning.
 
  • #11
sin() and cos() usually need inputs in radians, not degrees.
 
  • #12
FactChecker said:
sin() and cos() usually need inputs in radians, not degrees.

that's it. I did not know that. but converting degrees to radians brings me very close to my desired plot.

it's not perfect though. it looks weird. it is plotting more points than I told it to, and seems to be calculating more than what I think I told it to.
 
  • #13
grandpa2390 said:
timeToMaxHeight = -initialVelocity / gravity
You might want to rethink this.
 
  • Like
Likes grandpa2390 and FactChecker
  • #14
Orodruin said:
You might want to rethink this.

darn Typos. Even using descriptive variable names, I still miss them. That seems to do the trick. the domain and range are still a bit weird though. It isn't going to match the picture yet because the picture has drag and wind effects applied. but why is the y-axis starting so high?
 
  • #15
Where is your Y axis starting? It's difficult to know what your current code is (if you re-post, please remove all those accumulated blank lines.) If I make the changes that I think you should have made based on the comments, the plot looks reasonable to me.
 
  • #16
FactChecker said:
Where is your Y axis starting? It's difficult to know what your current code is (if you re-post, please remove all those accumulated blank lines.) If I make the changes that I think you should have made based on the comments, the plot looks reasonable to me.

ugh. I don't know where the blank spaces come from.
Code:
close all
clear all
clc
%%defining variables
tMin = 0 %seconds
angleWithHorizontal = 35*0.0174533 %degrees to radians
initialVelocity = 100 * .44704 %converting mph to m/s
tailWind = 10 * .44704 %converting mph to m/s
headWind = 10 *.44704 %converting mph to m/s
gravity = -9.8 %m/s^2
dt = .1 %change in time
mass = 1%unknown
initialVelocityY = initialVelocity * sin(angleWithHorizontal)
initialVelocityX = initialVelocity * cos(angleWithHorizontal)
timeToMaxHeight = -initialVelocityY / gravity
tMax = 2*timeToMaxHeight
initialPositionX = 0
initialPositionY = 0
accelerationX = 0
distanceTraveledX = initialPositionX + initialVelocityX * tMax + .5 * accelerationX * tMax^2

%%Position in Space Without Drag nor Wind
t = tMin:dt:tMax; % time steps
[j,k] = size(t);
velocityWithoutDragY(1) = initialVelocityY;
positionX(1) = initialPositionX;
positionY(1) = initialPositionY;

% calculate instantenous speeds and position??for i = 2:k
for i = 2:k
velocityWithoutDragY(i) = velocityWithoutDragY(i-1) + (gravity.*dt)
positionX(i) = positionX(i-1) + initialVelocityX*dt + .5*accelerationX.*dt^2
positionY(i) = positionY(i-1) + velocityWithoutDragY(i)*dt + .5*gravity.*dt^2
end

%%Plots

figure(1)
hold on
box on
plot(positionX,positionY,'-k')
set(gca,'Xtick',linspace(0,150,4),'fontsize',18,'Ytick',linspace(0,30,4))
set(gcf,'Color','w');
set(gcf,'Resize','on');
hold off
 
  • #17
That's the same plot that I expected. The Y axis goes up to 40 because it is marking in increments of 10 and the Y values go slightly over 30. Usually I initially let MATLAB decide it's own axis limits so I can easily get the whole picture and then I specify different limits like ylim([0 32]) if desired.
 
  • #18
FactChecker said:
That's the same plot that I expected. The Y axis goes up to 40 because it is marking in increments of 10 and the Y values go slightly over 30. Usually I initially let MATLAB decide it's own axis limits so I can easily get the whole picture and then I specify different limits like ylim([0 32]) if desired.

So how do you do that? where do type ylim([0 32]) at in the code? I thought linspace was supposed to handle that. but it isn't do a good job of it for me.
 
  • #19
After the plot and before the "hold off". I don't know why the linspace doesn't work, but you have two of them. The documentation I see for linspace does not apply to a plot.
 
  • Like
Likes grandpa2390
  • #20
FactChecker said:
After the plot and before the "hold off". I don't know why the linspace doesn't work, but you have two of them. The documentation I see for linspace does not apply to a plot.

Beautiful!
?temp_hash=0368d0b1322201e4e4b887a096f8180a.png

Don't worry, I'm not crazy. The actual plot I am working toward will include drag. And the ball will hit its peak at about X=70 and land somewhere at about X=120. But first things first. Have to figure out how to do the simple things (like simple kinematics) before I start tossing in more complicated things like drag :) :) :)
 

Attachments

  • Screen Shot 2018-03-06 at 5.11.16 PM.png
    Screen Shot 2018-03-06 at 5.11.16 PM.png
    5.6 KB · Views: 397
  • ?temp_hash=0368d0b1322201e4e4b887a096f8180a.png
    ?temp_hash=0368d0b1322201e4e4b887a096f8180a.png
    5.6 KB · Views: 267
  • Like
Likes FactChecker
  • #21
@FactChecker I hate to open an all-new thread for a dumb (or extremely simple) question. When am I supposed to end a line with a semi-colon. I've been throwing semi-colons behind lines that declare matrices because, that is just the way I have seen it done. is that correct?

and

and what exactly is this line doing?
Code:
t = tMin:dt:tMax; % time steps
[j,k] = size(t);

it looks like I am declaring a variable, t, and saying that it is equal to (tMax-tMin)/dt thereby giving me the total number of steps to be performed
then I am declaring a matrix j hat and k hat, each with a size equal to t.
so from 0 to 2 with dt=.5, t =4 and the matrix [j,k] has 4 positions for both j and k. which is then used in my for loop for i=2:k (which is 4). incidentally it seems, if I am following correctly, the j was extra that I didn't need.

but if I delete j and just have:
Code:
[k]=size(t);
I don't get an error, but I don't get a plot either.

Forgive me, I'm not trying to be a nuisance. : )
 
  • #22
FactChecker said:
(if you re-post, please remove all those accumulated blank lines.)
I removed most of the blank lines from the earlier code posted.

@grandpa2390, when you post code, add the type of code that it is (like C, Java, matlab, etc.). To do this, inside the opening code tag, add =matlab, with no spaces before or after =.

Like this:
[code=matlab]
% some code
[/code]
 
  • #23
Mark44 said:
I removed most of the blank lines from the earlier code posted.

@grandpa2390, when you post code, add the type of code that it is (like C, Java, matlab, etc.). To do this, inside the opening code tag, add =matlab, with no spaces before or after =.

Like this:
[code=matlab]
% some code
[/code]

let me try
Matlab:
t = tMin:dt:tMax; % time steps
[j,k] = size(t);

why is j and size in the same color? and clickable, but k isn't?

edit: I clicked on it and am reading the page it linked to :)
 
  • #24
grandpa2390 said:
let me try
Matlab:
t = tMin:dt:tMax; % time steps
[j,k] = size(t);

why is j and size in the same color? and clickable, but k isn't?

edit: I clicked on it and am reading the page it linked to :)
@FactChecker

ok so based on this link
Matlab:
size(t);
it seems I figured accurately what it meant. but I still don't understand why a matrix with two rows of size 4 is necessary when only one row is used? or I don't understand how it is being used?

edit: or maybe I don't understand what "Returns the number" means.
 
  • #25
A semicolon at the end of a MATLAB code line stops MATLAB from printing the result of the line. You want to do that so it will not fill the screen with data on lines that you already trust and do not need to see the results. When you are debugging, you might want to remove a semicolon at the end of a MATLAB line to see the results and make sure they are as expected. For instance, to see what is going on in your definition of t and size(t), remove the trailing semicolons to see that t is a 1xN matrix and the size function sets i and j to the dimensions. 'tMin:dt:tMax' is a loop from tMin to tMax in steps of dt.

Matlab:
>> tMin=0;
>> tMax=5;
>> dt = 1;
>> t = tMin:dt:tMax

t =

     0     1     2     3     4     5

>> [j,k] = size(t)

j =

     1k =

     6

I remove trailing semicolons to debug lines and then put them back when I'm confident of that line.

PS. A semicolon inside a matrix definition is different. It starts a new matrix definition row. There may be other uses of the semicolon inside a MATLAB line; I can't think of any now.
 
  • Like
Likes grandpa2390
  • #26
FactChecker said:
A semicolon at the end of a MATLAB code line stops MATLAB from printing the result of the line. You want to do that so it will not fill the screen with data on lines that you already trust and do not need to see the results. When you are debugging, you might want to remove a semicolon at the end of a MATLAB line to see the results and make sure they are as expected. For instance, to see what is going on in your definition of t and size(t), remove the trailing semicolons to see that t is a 1xN matrix and the size function sets i and j to the dimensions. 'tMin:dt:tMax' is a loop from tMin to tMax in steps of dt.

Matlab:
>> tMin=0;
>> tMax=5;
>> dt = 1;
>> t = tMin:dt:tMax

t =

     0     1     2     3     4     5

>> [j,k] = size(t)

j =

     1k =

     6

I remove trailing semicolons to debug lines and then put them back when I'm confident of that line.

PS. A semicolon inside a matrix definition is different. It starts a new matrix definition row. There may be other uses of the semicolon inside a MATLAB line; I can't think of any now.

excellent! I definitely do not want that :D
 
  • #27
@FactChecker
shoot, I was predefining the matrix for my new code, and I forgot the semicolon. so 10,000 zeroes are being shot at me lol
 
  • #28
@FactChecker
in true basic there is a command
Code:
mat redim x(i),y(i)

that is used to resize the dimensions of the matrices to a different value. So the matrix is predefined to be set at 5000, and at the end, the program figures out that only 1000 spaces are needed. so that command resizes the matrices.

is there something similar in MatLab?

edit:
Code:
x() and y() are the position of the projectile
dt = time step v_init = initial speed theta - launch angle
B_m = proportional to drag force= B2/m
sub calculate(x(),y(),dt,v_init,theta,B_m)
option angle degrees ! use degrees rather than radians
x{l) = 0
y(l) = 0
vx = v_init * cos(theta)
vy = v_init * sin(theta)
! initial velocity components
nmax = size(x) ! this is the number of elements in the array x()

for i = 2 to nmax
x(i) = x(i-1) + vx * dt
y(i) = y(i-1) + vy * dt
f = B_m * sqr(vxA2 + vyA2)
vy = vy - 9.8 * dt - f * vy * dt
vx = vx - f * vx * dt
if y(i) <= 0 then exit for

next i
a= -y(i) / y(i-1)
x(i) = (x(i) + a*x(i-1)) / (l+a)
y(i) = 0
mat redim x(i),y(i)
end sub
[/quote]
 
Last edited:

1. Why is my MatLab code for baseball not producing the correct results?

There could be several reasons for this. Some possible causes include errors in your code, incorrect input data, or a problem with your program's logic. It is important to carefully review your code and make sure it is written correctly and that your input data is accurate. You may also want to consider debugging your code to identify any logical errors.

2. How can I improve the performance of my MatLab code for baseball?

One way to improve performance is to optimize your code by using efficient algorithms and data structures. Additionally, you can try to reduce the number of variables and operations in your code, as well as avoiding unnecessary loops. It may also be helpful to use built-in functions and vectorization techniques to speed up your code.

3. I am getting an error message when running my MatLab code for baseball. What does it mean?

The error message is likely indicating a problem with your code or input data. You can refer to the documentation for MatLab or do a search online for the specific error message to get more information on what may be causing the error. You may also want to try debugging your code to identify and fix any issues.

4. Can I use MatLab code for baseball in conjunction with other programming languages?

Yes, MatLab has the ability to interface with other programming languages such as C, C++, and Java. This can be useful if you want to combine the strengths of MatLab with the strengths of another language. You can also use MatLab to call external functions or libraries written in other languages.

5. Is there a specific skill level required to write MatLab code for baseball?

While some prior programming experience is helpful, you do not need to be an expert to write MatLab code for baseball. MatLab has a user-friendly interface and provides many built-in functions and tools that make it accessible to users of all skill levels. With practice and patience, anyone can learn to write effective code for baseball using MatLab.

Similar threads

  • Introductory Physics Homework Help
2
Replies
36
Views
4K
  • Introductory Physics Homework Help
Replies
12
Views
1K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
4
Views
2K
  • Programming and Computer Science
Replies
7
Views
2K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
3
Views
2K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
6
Views
2K
  • MATLAB, Maple, Mathematica, LaTeX
2
Replies
41
Views
8K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
1
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
2K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
1
Views
939
Back
Top