How do I properly nicely comment this code?
Info
This question is closed. Reopen it to edit or answer.
Show older comments
My code:
v0 = 10
gamma = 0.1
for k=1:101
theta = 0.8444 * pi/4 + (k-51)*0.0001;
dt = 0.0000001;
x = 0;
y = 0;
vx = v0 * cos(theta);
vy = v0 * sin(theta);
x = x + dt * vx;
y = y + dt * vy;
while (y>0)
v = sqrt(vx*vx+vy*vy);
vx = vx - dt * gamma * vx;
vy = vy - dt * 9.81 - dt * gamma * vx;
x = x + dt * vx;
y = y + dt * vy;
end;
t(k) = theta
a(k) = x
end;
plot(a)
[vv, jv] = max(a)
t(jv) / (pi/4)
3 Comments
Bob Thompson
on 28 Oct 2019
Commenting is entirely creator dependent, so we can't tell you exactly how to comment it.
That being said, here are some practices I have learned to help others understand.
1) Have a header section with a brief outline of what the code does, when it was made, and possibly updates done to it. This can be especially useful if you have multiple versions of the same code and weren't sure what was changed.
2) Use section breaks to seperate different portions of your code. Often I like to keep inputs, processing, and results in separate sections.
3) Outline the purpose of things. We all know what are for loop does, but WHY it is being used is not always clear. This is really helpful for others to see when they are trying to understand your code structure.
It's impossible for someone else to say. Depends entirely who needs to understand it. Some code doesn't need commenting at all - if it does it's badly written. Other code needs comments however well written it is. I would recommend using variables with meaningful names instead of hard-coded 'magic numbers' like 9.81 and 0.8444, but I suppose comments on those would work well enough. I assume the 9.81 represents gravity so personally I would define
gravity = 9.81;
somewhere at the top and use that. Normally I define such things on the line before they are first used, but obviously not if that is in the middle of a loop.
Adam Danz
on 15 Dec 2019
Original question by OP in case it is deleted (this user has deleted many questions after being answered).
------------------------------------------------------------------
My code:
v0 = 10
gamma = 0.1
for k=1:101
theta = 0.8444 * pi/4 + (k-51)*0.0001;
dt = 0.0000001;
x = 0;
y = 0;
vx = v0 * cos(theta);
vy = v0 * sin(theta);
x = x + dt * vx;
y = y + dt * vy;
while (y>0)
v = sqrt(vx*vx+vy*vy);
vx = vx - dt * gamma * vx;
vy = vy - dt * 9.81 - dt * gamma * vx;
x = x + dt * vx;
y = y + dt * vy;
end;
t(k) = theta
a(k) = x
end;
plot(a)
[vv, jv] = max(a)
t(jv) / (pi/4)
Answers (0)
This question is closed.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!