Filter löschen
Filter löschen

Looping a program or multiple variables?

1 Ansicht (letzte 30 Tage)
Stuart
Stuart am 13 Apr. 2012
Hi,
I'm trying to determine the probability of a basketball shooting at the hoop on a correct line. Really basic at the moment, a line y=mx+c changes from a given point depending on the players shot angle phi.
I would like to run the program 100 times so that I can say player got ball on line x amount of times out of 100.
At the moment I am using the following code:
%Finding the maximum and minimum points of entering the hoop
%Initial launch data
x0=20;
y0=4;
n = 100;
q = randn(1,n)
mean_phi=atand((7.5-y0)/(26.425-x0));
sd_phi=2;
phi=mean_phi+sd_phi*q
%Gradient m given by
m=tand(phi)
%Constant c given as
c=y0-m*x0
%Using the quadratic formula
a=((m.^2)+1);
b=2*m*(c'-7.5)-52.85;
d=698.281+((c'-7.5).^2)-0.01;
%Find the coordinates of intersection if possible
if ((b.^2)-4*a*d)>0
xp=(-b+sqrt((b.^2)-(4*a*d)))/(2*a')
xm=(-b-sqrt((b.^2)-(4*a*d)))/(2*a')
yp=m*xp'+c
ym=m*xm'+c
else
fprintf('The ball missed the hoop\n')
end
%Ball enters hoop if ball lands between (xm,ym) and (xp,yp)
o=(27-x0)/99
x=x0:o:27;
y=(m'*x)+c;
plot (x,y)
But right at the end when I want to plot a graph between the players position an x =27, the straight equation has matrices that don't match.
would it be better to loop the program using i=100 or can someone see a glaring error in my code.
Any help would be much appreciated.
Cheers
Stu
  2 Kommentare
Walter Roberson
Walter Roberson am 13 Apr. 2012
Consider using
x = linspace(x0, 27, 100);
instead of your current "o" and "x" code.
Stuart
Stuart am 16 Apr. 2012
Thanks walter, but do you have any idea about the random iteration part?

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Sargondjani
Sargondjani am 16 Apr. 2012
you should keep it in vectorized form, unless you are really new to matlab as looping is usually easier to follow/debug
about your error: if the sizes of the matrices don't match, and you expected them to match, then you just have to figure out why they differ. really that simple...
you can do [rows_X,cols_X]=size(X) to determine the size of a variable in every step... see where it goes wrong
  2 Kommentare
Stuart
Stuart am 16 Apr. 2012
Having read through my code and your answer, I think I've confused myself with what I want to achieve.
I would like 100 plotted lines of form y=mx+c where x is always between x0 and 27. The things that change are m and c, however they are paired together, as you can see in my code, c is determined by m.
So do I have to perform the loop in a different way?
Sargondjani
Sargondjani am 16 Apr. 2012
i hate decoding matlab code, so can you tell where you want the 100 lines for:
100 draws of phi
or
100 different 'starting values' for x

Melden Sie sich an, um zu kommentieren.

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by