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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by