# Calculate Inflation rate (yearly, quarterly)

13 views (last 30 days)
Gustav Analog on 23 Feb 2022
Answered: Jaynik on 15 Jul 2024
I created time series data with the consumer price index (among others – see the screenshot), the consumer price index I need is CPIAUCSL).
I want to calculate the inflation rate (year-on-year and quarter-on-quarter).
First, I converted the data with convert2annual/convert2quarterly.
Now, I need to write the loop to calculate the inflation rate.
I used the code:
CPI_annual = data_annual(:,6); % define variable
for jj = 2:77;
CPI_inflation(jj) = (CPI_annual(jj)-CPI_annual(jj-1))./CPI_annual(jj-1)*100; %create the loop
end
Tbh, I am absolute beginner and did not find out why it is not working. If anybody can help me with her or his knowledge, I would be really thankful.

Jaynik on 15 Jul 2024
Hi Gustav,
The approach to calculate the inflation rate based on the Consumer Price Index is correct. The inflation rate is typically calculated as the percentage change in the CPI from one period to the next.
However, you mentioned that your code is not working. One potential issue could be that the variable CPI_inflation is not pre-allocated before the loop, which can cause issues in MATLAB. Another issue might be related to indexing. The way you are extracting CPI_annual using data_annual(:,6) may not return a numeric array directly. Instead, it returns a table with one column. You need to access the data within the table. Following is a sample code for the same:
CPI_annual = data_annual.CPIAUCSL; % define variable
CPI_inflation = zeros(size(CPI_annual)); % pre-allocate the array
for jj = 2:length(CPI_annual);
CPI_inflation(jj) = (CPI_annual(jj)-CPI_annual(jj-1))./CPI_annual(jj-1)*100;
end
Also, use size(CPI_annual) to dynamically determine the number of rows. This ensures that the loop runs for each element in CPI_annual, regardless of how many elements there are.
It would be beneficial if you could share the specific issue so that I can assist you more effectively.
Hope this helps!