Combining two for loops into a nested loop

4 次查看(过去 30 天)
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