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

 Akzeptierte Antwort

Guillaume
Guillaume am 14 Dez. 2016
Bearbeitet: Guillaume am 14 Dez. 2016

0 Stimmen

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);

Weitere Antworten (1)

Cyrill Buehler
Cyrill Buehler am 14 Dez. 2016

0 Stimmen

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

Kategorien

Community Treasure Hunt

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

Start Hunting!

Translated by