Suggestions for improving efficiency of code

1 vue (au cours des 30 derniers jours)
Dave
Dave le 25 Mar 2021
Modifié(e) : Jan le 26 Mar 2021
Hey all,
Just working on some things to teach myself different Matlab techniques. I've put together some code that looks at downloaded .csv files containing Covid data and plot the data out of selected files. The code works, with one warning. I would appreciate any suggestions to improve this code.
The warning is" Warning: Column headers from the file were modified to make them valid MATLAB identifiers beforecreating variable names for the table. The original column headers are saved in the VariableDescriptions property. Set 'PreserveVariableNames' to true to use the original column headers as table variable names."
%%
clc,clear,clf;
%% Select fles to compare and write to cell array.
[filenames, folder] = uigetfile('*.csv', 'Select the data files','MultiSelect','on');
% If only one file selected filenames is a class char and
% needs to be changed to a 1x1 cell array.
tf = isa(filenames,'char');
if tf == 1
filenames = {filenames};
end
%% Extract State names from file names
statenames = extractBetween(filenames,"__",".");
%% Setup the Import Options and import the data
% This was just taken from the MATLAB built in Import Tool.
opts = delimitedTextImportOptions("NumVariables", 3);
% Specify range and delimiter
opts.DataLines = [5, Inf];
opts.Delimiter = ",";
% Specify column names and types
opts.VariableNames = ["Date", "TotalCases", "DayRateper100000"];
opts.VariableTypes = ["string", "double", "double"];
% Specify file level properties
opts.ExtraColumnsRule = "ignore";
opts.EmptyLineRule = "read";
% Specify variable properties
opts = setvaropts(opts, "Date", "WhitespaceRule", "preserve");
opts = setvaropts(opts, "Date", "EmptyFieldRule", "auto");
%% Open figure and set axis labes
cd(folder);
figure(1)
grid on;
ylabel('7 Day Rate / 100000')
xlabel('Date')
hold on;
%% Import data and create plot for each pass
for i = 1:numel(filenames)
tmp = readtable(string(filenames{i}));
tmp = flip(tmp);
tmp.Date = datetime(tmp.Date,'InputFormat','MMM dd yyyy');
plot(tmp.Date, tmp.x7_DayRatePer100000,'LineWidth',2)
end
hold off;
%% Add Legend for each selected file.
legend(statenames{1:end},'Location','best','Interpreter','none');

Réponse acceptée

Jan
Jan le 25 Mar 2021
Modifié(e) : Jan le 26 Mar 2021
You can replace:
tf = isa(filenames,'char');
if tf == 1
filenames = {filenames};
end
by
filenames = cellstr(filenames);
It is a good programming practize not to change the current directory by cd(). Use absolute file names instead. The problem with cd() is, that a callback of a timer or a GUI might include a cd() also. Then the current folder can changed unepectedly.
% Nope: cd(folder);
...
tmp = readtable(fullfile(folder, filenames{i})); % No need for string()
The flip command tries to be smart as other Matlab commands and guesses, which dimension you want to flip. This can be criticial, if the data has one row or column only and you exepct something else. Therefore it is recommended to specify the wanted dimension in every case. Although this costs some tenth of a second for typing, it can save hours or days for debugging.
tmp = flip(tmp, 1);
The first input of legend can be a cell string, so this is slightly leaner:
legend(statenames, 'Location', 'best', 'Interpreter', 'none');
  1 commentaire
Dave
Dave le 25 Mar 2021
Thanks, appreciate the help.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Language Fundamentals dans Help Center et File Exchange

Produits


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by