Improving the compactness of code

1 vue (au cours des 30 derniers jours)
Wouter Wizard
Wouter Wizard le 7 Nov 2019
Commenté : Wouter Wizard le 7 Nov 2019
Hi all,
I am working on four string arrays on which I performed some structuring. I am new to Matlab so I am very happy that the code finally works. However, I would like to improve the code by using loops or statements to improve the compactness. For each of the four data sets the last three operations are performed on all arrays, therefore I would like to use a structure that can reduce the number of lines and perform a operation that simplifies to one operation.
I tried using a for-loop but this did not work out since I didnt know how to state the i/j/k for the different data sets. Could anyone explain me how to approach such a problem?
In the code below you can see the operations that are performed on each dataset:
% Importing and sorting population data
pop = tsv2cell('Population.tsv');
pop = sortrows(pop(2:end,:),1);
pop(:,[2:4,11:end]) = []; % Delete column 2,3,4
pop = erase(pop,[" e", " b"]); % Delete non-numerical attributes
pop = standardizeMissing(pop,':'); % Find invalid data
pop = rmmissing(pop); % Remove rows with invalid data
% Importing and sorting GDP data
gdp = tsv2cell('GDP.tsv');
gdp = sortrows(gdp(2:end,:),1);
gdp(:,[2,3,4,11:end]) = [];
gdp = erase(gdp,[" e", " b"]);
gdp = standardizeMissing(gdp,':');
gdp = rmmissing(gdp);
% Importing and sorting passenger data
fp = tsv2cell('Flightpassengers.tsv');
fp(38:end,:) = [];
fp(:,[2:5]) = [];
fp = erase(fp,[" e", " b"]);
fp = sortrows(fp(2:end,:),1);
fp = standardizeMissing(fp,':');
fp = rmmissing(fp);
%Importing and sorting QoL data
lr = tsv2cell('LifeRating.tsv');
lr(3:36,8) = lr(38:end,7);
lr(37:end,:) = [];
lr(:,[2:6,9:end]) = [];
lr = sortrows(lr(2:end,:),1);
lr = erase(lr,[" e", " b"]);
lr = standardizeMissing(lr,':');
lr = rmmissing(lr);

Réponses (1)

Turlough Hughes
Turlough Hughes le 7 Nov 2019
You could put them in a structure as follows:
s.pop=pop; s.gdp=gdp; s.fp=fp; s.lr=lr;
and then to run the loop you just iterate through each field in the structure, s:
f=fieldnames(s);
for c=1:length(f)
s.(f{c})=erase(s.(f{c}),[" e", " b"]);
s.(f{c})=standardizeMissing(s.(f{c}),':');
s.(f{c})=rmmissing(s.(f{c}));
end
This should be fine but i'm not certain as I don't have your data, if it doesn't could you attach the datasets in the original question.
  3 commentaires
Turlough Hughes
Turlough Hughes le 7 Nov 2019
Can you upload the .tsv files?
Wouter Wizard
Wouter Wizard le 7 Nov 2019
I have placed them in a ZIP since tsv is not supported. Thanks for your help!

Connectez-vous pour commenter.

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by