Clear Filters
Clear Filters

How can can this code be made more efficient?

2 views (last 30 days)
% The intial heights, plus gravity and velocity
i_h = 0:0.25:95;
t_h = 0:0.25:105;
g_h = 0:0.25:115;
j_h = 0:0.25:125;
k_h = 0:0.25:135;
l_h = 0:0.25:145;
a_h = 0:0.25:155;
z_h = 0:0.25:165;
x_h = 0:0.25:175;
c_h = 0:0.25:185;
v_h = 0:0.25:195;
g = 9.81;
v = 85;
% Equations: d is distance and distance is relative to the inital height equation present
d_0 = (v*sqrt(2*i_h/g));
d_1 = (v*sqrt(2*t_h/g));
d_2 = (v*sqrt(2*g_h/g));
d_3 = (v*sqrt(2*j_h/g));
d_4 = (v*sqrt(2*k_h/g));
d_5 = (v*sqrt(2*l_h/g));
d_6 = (v*sqrt(2*a_h/g));
d_7 = (v*sqrt(2*z_h/g));
d_8 = (v*sqrt(2*x_h/g));
d_9 = (v*sqrt(2*c_h/g));
d_10 = (v*sqrt(2*v_h/g));
%plot
figure;
plot(d_0, i_h(end)-i_h)
hold on
plot(d_1, t_h(end)-t_h)
hold on
plot(d_2, g_h(end)-g_h)
hold on
plot(d_3, j_h(end)-j_h)
hold on
plot(d_4, k_h(end)-k_h)
hold on
plot(d_5, l_h(end)-l_h)
hold on
plot(d_6, a_h(end)-a_h)
hold on
plot(d_7, z_h(end)-z_h)
hold on
plot(d_8, x_h(end)-x_h)
hold on
plot(d_9, c_h(end)-c_h)
hold on
plot(d_10, v_h(end)-v_h)
hold off
title 'i_h'
ylabel ('Height (m)')
xlabel ('Distance (m)')
legend('95 metres', '105 Metres', '115 Metres', '125 Metres', '135 Metres', '145 Metres', '155 Metres', '165 Metres', '175 Metres', '185 Metres', '195 Metres')
grid on
  1 Comment
Sam Chak
Sam Chak on 8 Oct 2023
Hi @Thomas,
Your new question is related to coding efficiency. By the way, has the plotting issue from your previous question been technically resolved? Link to the previous question.

Sign in to comment.

Accepted Answer

Dyuman Joshi
Dyuman Joshi on 8 Oct 2023
Instead of dynamically naming variables, use a for loop.
%Constants
g = 9.81;
v = 85;
%Arrays of values to be used
vec = 95:10:195;
figure
hold on
for k=vec
arr_k = 0:0.25:k;
d_k = v*sqrt(2*arr_k/g);
plot(d_k, arr_k(end)-arr_k)
end
hold off
grid on
title('i_h')
ylabel('Height (m)')
xlabel('Distance (m)')
%Take advantage of the properties of strings to make the legend
legend(vec + " Metres")

More Answers (0)

Categories

Find more on 2-D and 3-D Plots in Help Center and File Exchange

Products


Release

R2023a

Community Treasure Hunt

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

Start Hunting!