Combining two for loops into a nested loop

조회 수: 4 (최근 30일)
Wietze Zijpp
Wietze Zijpp 2022년 4월 4일
편집: Wietze Zijpp 2022년 4월 5일
Suppose I have a forloop that yields a 1x3 output
for i = [1:3] % 3 months
mdl = fitlm(X((30*i-30+1):i*30,:),Y((30*i-30+1):i*30,3)) % regression
% for one month of the regressors X on Y for stock 1.
montherrors(:,i) = mdl.Residuals(:,1) % isolate the daily errors
errors = table2array(montherrors) % convert to array so I can perform
% calculations
stdev = std(errors, 1)
idio_three = stdev * sqrt(ndays) % so obtain 3 monthly idio-risks
end
And another loop that also yields a 1x3 output
i = 1 % so no loop over i
for j = [1:3] % 3 months
mdl = fitlm(X((30*i-30+1):i*30,:),Y((30*i-30+1):i*30,j)) % regression
% for one month of the regressors X on Y for stock 1.
montherrors(:,j) = mdl.Residuals(:,1) % isolate the daily errors
errors = table2array(montherrors) % convert to array so I can perform
% calculations
stdev = std(errors, 1)
idio_j = stdev * sqrt(ndays) % so obtain 3 monthly idio-risks
end
Now I would like to combine the two to obtain a 3x3 matrix output. I have tried multiple strategies but cant seem to figure it out.
I tried
for j = [1:3] % number of stocks 1 , 2 and 3
for i = [1:3] % 30*180 = 5400 days
mdl = fitlm(X((30*i-30+1):i*30,:),Y((30*i-30+1):i*30,j)) % regression
% for one month of the regressors X on Y for stock 1.
montherrors(:,(i*j)) = mdl.Residuals(:,1) % daily errors for
errors = table2array(montherrors) % convert to array so I can perform
% calculations
stdev = std(errors, 1)
idio_one(j,:) = stdev * sqrt(ndays) % so obtain 3 monthly idio-risks
end
end
But then i get the error Cannot create a table variable with a discontiguous index.

채택된 답변

MJFcoNaN
MJFcoNaN 2022년 4월 5일
Please check whether this step is correct:
montherrors(:,(i*j)) = mdl.Residuals(:,1)
Maybe you need one of these:
%(1)
montherrors(:,(i)) = mdl.Residuals(:,1)
% or (2)
count = 0;
for j = [1:3] % number of stocks 1 , 2 and 3
for i = [1:3]
count=count+1;
% ...
montherrors(:, count) = mdl.Residuals(:,1)
% ...
end
end
  댓글 수: 1
Wietze Zijpp
Wietze Zijpp 2022년 4월 5일
편집: Wietze Zijpp 2022년 4월 5일
I had tried
montherrors(:,(i*j)) = mdl.Residuals(:,1)
But that gives the error: Cannot create a table variable with a discontiguous index.
When using your proposed count the loop acttually works !!
Thank you for your help

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by