MATLAB Answers

0

Traverse a nested for loop with strings as one index and int as another.

Asked by Nathan Nguyen on 23 Oct 2019 at 0:29
Latest activity Answered by congly vaness on 23 Oct 2019 at 1:55
I have a list of 10 countries, and I have extracted the GDP, Population, CO2 emissions, and year vectors for each. I would like to calculate the CO2 emissions per capita over the GDP per capita. To do so, I need a for loop. Rather than writing 10 for loops, I am trying to use one nested for loop, changing the name of the country each time. The problem is, I can't convert the String to the vector.
For example, I have US_GDP and US_Populationas a vector name, but trying
GDP = countryName + "_GDP"
Population = countryName + "_Population"
GDPperCapita = GDP(index) / Population(index)
just results in trying to divide a string by a string. Any tips, or should I just write the 10 for loops separately.

  0 Comments

Sign in to comment.

Products


Release

R2019a

2 Answers

Answer by Cris LaPierre
on 23 Oct 2019 at 1:25
Edited by Cris LaPierre
on 23 Oct 2019 at 1:25

When working with strings, the "+" is used for concatenation. Your result, then, is strings, not variables.
It depends what your data looks like but I would pursue looking into using a table.

  0 Comments

Sign in to comment.


Answer by congly vaness on 23 Oct 2019 at 1:55

I thinks so! When working with strings, the "+" is used for concatenation. Your result, then, is strings, not variables.

  0 Comments

Sign in to comment.