Hi there
I have many entrys in my workspace, let's say USApopulation, GBRpopulation, ESPpopulation... and so on for several countries and time periods.
How can I write a loop for a general case?
For example, let's assume I want to divide each population series by 2:
CountryNames = ['USA' 'GBR' 'ESP' ... ];
for i = [1:length(CountryNames)];
ReducedCountryPopulation(i,:) = [CountryNames{i}'population']./2;
end;
Thank you very much!! :)

 Réponse acceptée

Guillaume
Guillaume le 14 Déc 2016
Modifié(e) : Guillaume le 14 Déc 2016

0 votes

Way to go in answering your own question and not giving anybody else a chance to offer a different option!
This is completely the wrong approach! You're now going to have tons of eval in your code, making it slow (the content of the eval can't be optimised by matlab), hard to debug (mlint can't highlight errors in the eval, you can't step through the eval code) and more complicated than it needs to be
Much, much better would be to change the way you actually store your data. Do not embed metadata in a variable names. Instead of having a separate variable for each nation, use a single variable for all and an index to access each nation. Two easy options: containers.Map or table. Example using a map:
%first, getting rid of all those variables:
CountryNames = {'USA'; 'MEX'; 'ESP'};
CountryPopulation = containers.Map;
for countryidx = 1:numel(CountryNames)
CountryPopulation(CountryNames{countryidx}) = eval([CountryNames{countryidx}, 'population']);
end
%calculate the ratioed countries population
%No need for eval anymore
MeanRatioPopulation = containers.Map(CountryPopulation.keys, cellfun(@(pop) pop / 2, CountryPopulation.values, 'UniformOutput', false);

Plus de réponses (1)

Cyrill Buehler
Cyrill Buehler le 14 Déc 2016

0 votes

Edit:
I managed it:
CountryNames = ['USA'; 'MEX'; 'ESP'];
for i = [1: size(CountryNames,1) ];
varName = [CountryNames(i,:) 'population'];
eval(['mean_Ratio' varName ' = (' varName ')./2 ;']);
end

Catégories

En savoir plus sur Debugging and Improving Code dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by