Could someone please optimize this code?

1 回表示 (過去 30 日間)
The Merchant
The Merchant 2019 年 10 月 28 日
コメント済み: Adam Danz 2019 年 12 月 15 日
Could someone please optimize this code?
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)
  2 件のコメント
John D'Errico
John D'Errico 2019 年 10 月 29 日
It can be terribly difficult to optimize code if we are not told what the code is supposed to do. A few words of explanation would be a great help there.
Adam Danz
Adam Danz 2019 年 12 月 15 日
Original question by OP in case it is deleted (this user has deleted many questions after being answered).
------------------------------------------------------------------
Could someone please optimize this code?
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)

サインインしてコメントする。

回答 (1 件)

Bob Thompson
Bob Thompson 2019 年 10 月 28 日
I don't know about 'optimized,' but I'm pretty sure you can remove the entire for loop by vectorizing. Also, suppressing your values will actually do a surprising amount to speed up run time. Anything visual takes a lot more time and power to output, even just numbers and letters.
v0 = 10;
gamma = 0.1;
range = (-50:50);
theta = 0.8444 * pi/4 + range.*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); % What does this do? It isn't used anywhere
vx = vx - dt * gamma * vx;
vy = vy - dt * 9.81 - dt * gamma * vx;
x = x + dt * vx;
y = y + dt * vy;
end
plot(x)
[vv, jv] = max(x);
t(jv) ./ (pi/4);
I suspect part of the problem is that your code doesn't ever actually produce a negative value for y. The first value is slightly >0, but after that all you're doing is adding more positive values.
  3 件のコメント
The Merchant
The Merchant 2019 年 10 月 28 日
I get the following error:
Unrecognized function or variable 't'.
Bob Thompson
Bob Thompson 2019 年 10 月 29 日
I never got to t because the while loop was always positive and never stopped running. I would agree with the error that it is undefined.

サインインしてコメントする。

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by