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 Exchange에서 File 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