 # 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?

``````A=randn(1000,50);
window_size=10;
n_windows=size(A,1)/window_size;
var_results=NaN(n_windows,size(A,2));
for window_iter=1:n_windows
var_results(window_iter,:)=var(detrend(A((window_iter-1)*window_size+1:window_iter*window_size,:)));
end
var_results_mean=mean(var_results);
``````
1 Like

hi professor,
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

``````N_sim=50;
N_periods=100;
rec_count=zeros(N_sim,1);
for ii=1:N_sim
temp=sign(diff(log(Y((ii-1)*N_periods+1:ii*N_periods))));
start_recession=0;
for jj=2:length(temp)
if all(temp(jj-1:jj)<0)
if start_recession==0
start_recession=1;
rec_count(ii,1)=rec_count(ii,1)+1;
else
%do nothing, still in same recession
end
else
start_recession=0;
end
end
end

total=sum(rec_count);
``````
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?

Best

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

Thanks!!

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,