Doing loops with Matlab

Hi Professor,
I would like to know if there is matrix A=1000*50;

for each colum:

I want to first detrend and then calculate the variance for each 10 numbers, ie. var(detrend(1th:10th), var(detrend(11th:20th)…var(detrend(991th:1000th),
then take the average of these 100 variances.

finally I want to do the same for the rest 49 colums and present the results for all 50 colums in a row.

Please could you provide me with the matlab loops functions?

for window_iter=1:n_windows
1 Like

hi professor,
further to your previous reply, could I ask a more complicated question?
if I have 50simulations of output stacked up with each containing 100 periods (quarters), so it’s 5000*1 matrix. I want to define at least two consecutive quarters of negative output growth as a recession, and I want to count how many recessions would occur on average over 50simulations?

if simulation 1 gives us 3 recessions over 100 periods (at least two consecutive periods of negative growth) , simulation 2 gives us 5 recessions over 100 periods, the average would be 4…

hopefully you can what I meant. thanks in advance!

Yes, that computation would be correct. Or was your question how to code this?

1 Like

Yes, how to code this…

Something along the lines of

for ii=1:N_sim
    for jj=2:length(temp)
        if all(temp(jj-1:jj)<0)
            if start_recession==0
                %do nothing, still in same recession

1 Like

Many thanks professor! cannot believe my eyes. The code works pefectly, giving me exactly what I want. Btw, please could you offer some instructions on how to develop coding skills specifically with Matlab? Have you refered to any textbooks or learning materials on the early stages? The question that always bothers me is where do you get to know the functions suitable to carry our specific tasks?


Further to my previous question, is it possible to calculate the average length and depth of recessions over 50 simulations?

if length = the number of periods of negative GDP growth (no.>=2)
depth = the number of periods after recesson it takes to recover to the pre-crisis level


Yes, that is possible, but quite some work. The trick with Matlab as with any programming language is not to know the functions but rather have a good idea what an appropriate algorithm for the task at hand is.
For the tasks above, within the loop you need to keep track not just of whether a recession continues but rather count how long it takes.

1 Like

Hi Professor,

Please could you indicate me
given 50 simulations of interest rates, and each contains 100 periods,

how to calculate how many times the nominal interest rates ® falling into the ZLB over the 50 simulations that contains 100 periods each? if we define falling ZLB as at least two consecutive periods of 0.01 ( exogenous lower bound of our choice)?

in my model, once the interest rate hits the ZLB, it won’t be able to get any lower, so it stays at the ZLB till it exits…

Thanks in advance!