Getting MatLab to read a datatable for changing variable
2 views (last 30 days)
Show older comments
I'm using DICE-MPC in matlab to work on a project, and I'd like to introduce an exogenous variable with a table of readable data.
In the existing model 'i' represents the year that the model is operating in, and it changes by i+1 with every loop.
I am introducing a datatable with a readable population variable that changes with each i, for example when i=1 , population = 1000; i=2 , population = 1010 and so on in a table with the two columns as i and population. This is as a CSV file but I can easily change this to whatever may work best.
I'd like MatLab to read the population column at the i that corresponds with the one being used in the loop. ie when i = 1, it reads row 1 of my datatable and my variable POPULATION becomes 1000, then with the next loop when i increases to i=2 it reads row 2 and POPULATION = 1010 - so that I can than go on to use POPULATION as a variable in different formulae in dice dynamics.
How do I get MatLab to use/read the right population variable with each loop and increase in i?
2 Comments
Stephen23
on 14 Feb 2024
Unless the file is so large that it cannot be imported all at once into memory, the easiest approach would be to import the CSV file using e.g. READTABLE and then select the required columns/variables using e.g. the variable names or indexing.
Answers (1)
Ronit
on 23 Feb 2024
Hi Emma,
To process your table and extract the population numbers for each year, you can utilize the MATLAB code snippet provided below. Please treat this as a template and adjust it to fit the specifics of your dataset.
populationTable = readtable('filename.csv'); % Replace 'filename' with your actual file name
N = height(populationTable); % Total rows of the table
for i = 1:N
% Access the population for the current year
POPULATION = populationTable.Population(i); % Replace 'Population' with the actual column name
% Now you can use the variable POPULATION in your DICE dynamics equations
% ... (your DICE model calculations)
end
This will read the population for year ‘i from your table and assign it to the variable “POPULATION” in each iteration of the loop. You can then use “POPULATION” in any calculations or formulae within the loop.
Here is a documentation for further details about extracting data from table in MATLAB: https://www.mathworks.com/help/matlab/matlab_prog/access-data-in-a-table.html#mw_f59a5df5-e7b6-42e3-a1ca-69196ee9d9b7
Hope this helps!
0 Comments
See Also
Categories
Find more on Data Import and Analysis in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!