Reducing script repetitiveness and length
Mostrar comentarios más antiguos
I'm curious as to what methods I could implement to reduce the length of the script, but also the repetitiveness.
% Before any script, clear
clear
clc
% 1.1 - Reading data file
fileID = fopen('VELOCITY.txt','r');
formatSpec = '%f';
V = fscanf(fileID,formatSpec);
% 1.2 - Calculating Acceleration from Velocity
dV = gradient(V);
dt = 0.5;
a = dV./dt;
t=(0:0.5:25.5);
% 1.3 - Plot Velocity and Acceleration
plot(t, V, '-r', 'LineWidth', 2)
xlabel('Time (s)')
ylabel('Velocity (m/s)')
title('Velocity against Acceleration')
xlim([0, 25.5])
hold on
yyaxis right
plot(t, a, '-g', 'LineWidth', 2)
ylabel('Acceleration (m/s^2)')
legend('Velocity','Acceleration')
legend('Location','eastoutside')
grid on
hold off
cla reset
% 1.4 - 2nd Order Polynomial to given Velocity
p2 = polyfit(t,V,2);
VSmooth2 = polyval(p2,t);
plot(t, VSmooth2, '-b', 'LineWidth', 2)
xlabel('Time (s)')
ylabel('Velocity (m/s)')
title('Smoothed Velocity of 2nd Order Polynomial')
legend('2nd Order Smoothed Velocity')
legend('Location','eastoutside')
xlim([0, 25.5])
grid on
cla reset
% 1.5 - 2nd order Smoothed Acceleration based upon Smoothed Velocity
dV2 = gradient(VSmooth2);
dt = 0.5;
aSmooth2 = dV2./dt;
% 1.6 - Original Velocity, Acceleration and 2nd Order Smoothed Acceleration
plot(t, V, '-r', 'LineWidth', 2)
xlabel('Time (s)')
ylabel('Velocity (m/s)')
title('Velocity, Acceleration and Smoothed Acceleration of 2nd Order Polynomial')
hold on
yyaxis right
plot(t, a, '-g', 'LineWidth', 2)
ylabel('Acceleration (m/s^2)')
hold off
hold on
plot(t, aSmooth2, '-m', 'LineWidth', 2)
legend('Velocity','Acceleration','2nd Order Smoothed Acceleration')
legend('Location','eastoutside')
xlim([0, 25.5])
grid on
hold off
cla reset
% 1.7 - 4th Order Polynominal to given Velocity
p4 = polyfit(t,V,4);
VSmooth4 = polyval(p4,t);
plot(t, VSmooth4, 'Color','#EDB120', 'LineWidth', 2)
title('Smoothed Velocity of 4th Order Polynomial')
legend('4th Order Smoothed Velocity')
legend('Location','eastoutside')
xlim([0, 25.5])
grid on
cla reset
% 1.8 - 4th Order Smoothed Acceleration based upon Smoothed Velocity
dV4 = gradient(VSmooth4);
dt = 0.5;
aSmooth4 = dV4./dt;
% 1.9 - Original Velocity, Acceleration and 4th Order Smoothed Acceleration
plot(t, V, '-r', 'LineWidth', 2)
xlabel('Time (s)')
ylabel('Velocity (m/s)')
title('Velocity, Acceleration and Smoothed Acceleration of 4th Order Polynomial')
hold on
yyaxis right
plot(t, a, '-g', 'LineWidth', 2)
ylabel('Acceleration (m/s^2)')
grid on
hold off
hold on
plot(t, aSmooth4, '-c', 'LineWidth', 2)
legend('Velocity','Acceleration','4th Order Smoothed Acceleration')
legend('Location','eastoutside')
xlim([0, 25.5])
hold off
cla reset
% 1.10 - 2nd Order Smoothed Acceleration against 4th Order Smoothed Acceleration
plot(t, aSmooth2, '-m', 'LineWidth', 2)
xlabel('Time (s)')
ylabel('Acceleration (m/s^2)')
title('Smoothed Acceleration of 2nd and 4th Order Polynomials')
hold off
hold on
plot(t, aSmooth4, '-c', 'LineWidth', 2)
legend('2nd Order Smoothed Acceleration','4th Order Smoothed Acceleration')
legend('Location','eastoutside')
xlim([0, 25.5])
ylim([0, 30])
grid on
hold off
5 comentarios
DGM
el 15 de Mzo. de 2021
I'm not really sure how much shorter a script needs to be, but generally if the goal is to eliminate repetition of code, look to write a function. Find a pattern of code that's being repeated, find a way to separate the parameters that are unique to each instance, and write an external function file that can take those parameters.
You might find that the parameters themselves (plot labels, etc) are often long char arrays and take up a lot of room in repeated blocks anyway. This might limit the amount of lines saved by moving the plotting routine to a different file. If it's strictly line count that's to be avoided, you may be able to save a few lines by cramming multiple character array parameters into a single cell array for each case. (e.g. theselabels={'Time (s)', 'Acceleration (m/s^2)'};) That would really only be trading line count for line length and readability.
Daniel Smith
el 16 de Mzo. de 2021
Jan
el 16 de Mzo. de 2021
There are no "if loops" in any programming language I know.
Daniel Smith
el 16 de Mzo. de 2021
Editada: Jan
el 17 de Mzo. de 2021
DGM
el 16 de Mzo. de 2021
Well, I'm sure you could find a way to use a loop, but considering that the bulk of the code here is plotting and plot configuration, you might be complicating matters by then trying to find a way to index through all the various axes labels, etc.
Once a routine is reduced to a function, calling it would only take a line or two. Writing a flat script would (in my questionable opinion) be sufficiently compact and readable. Something like
% plot this thing
t=1:10;
x=thisisa(functionof([bunch of numbers]));
title='this thing';
labels={'this is time','this is x'};
myplotroutine(t, x, title, labels, myselectedlinecolor, thisisxrange, thisisyrange, otheroptions);
% plot this other thing
y=thisisa(functionof(x));
title='this other thing';
labels={'this is time','this is y'};
myplotroutine(t, y, title, labels, adifferentlinecolor, thisisxrange, thisisyrange, differentoptions);
% plot a third thing
doesn't really seem unreasonably cluttered. It could certainly be made more compact, but how compact does a plotting script need to be? It's really up to you and your requirements.
Respuestas (1)
Athul Prakash
el 18 de Mzo. de 2021
Hi Daniel,
Your code doesn't seem extra complicated. Writing each plot after each calculation is one way to keep things simple and readable. However, since you mentioned repetitiveness, perhaps you could use a helper function to plot. You may pass all the plotting arguments, such as axes limits, legend(s) etc. This way, you can use default values for the function arguments to scrap away most of the redundant values, such as xlimit being [0 25.5] always.
% function plotHelper(xval, yval, <more plotting params>... )
% Use inputParser object (or function argument validation)
% ... to set default plotting options.
InputParser:
Function Argument Validation
Hope it helps.
Categorías
Más información sobre Axis Labels en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!