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

 採用された回答

Guillaume
Guillaume 2016 年 12 月 14 日
編集済み: Guillaume 2016 年 12 月 14 日

0 投票

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

その他の回答 (1 件)

Cyrill Buehler
Cyrill Buehler 2016 年 12 月 14 日

0 投票

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

カテゴリ

ヘルプ センター および File ExchangeFile Operations についてさらに検索

質問済み:

2016 年 12 月 14 日

編集済み:

2016 年 12 月 14 日

Community Treasure Hunt

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

Start Hunting!

Translated by