Loop concerning workspace names

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!! :)

 Accepted Answer

Guillaume
Guillaume on 14 Dec 2016
Edited: Guillaume on 14 Dec 2016
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);

More Answers (1)

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

Categories

Asked:

on 14 Dec 2016

Edited:

on 14 Dec 2016

Community Treasure Hunt

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

Start Hunting!