Combining two for loops into a nested loop

2 vues (au cours des 30 derniers jours)
Wietze Zijpp
Wietze Zijpp le 4 Avr 2022
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.

Réponse acceptée

MJFcoNaN
MJFcoNaN le 5 Avr 2022
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 commentaire
Wietze Zijpp
Wietze Zijpp le 5 Avr 2022
Modifié(e) : Wietze Zijpp le 5 Avr 2022
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

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by