Combining two for loops into a nested loop
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Wietze Zijpp
el 4 de Abr. de 2022
Editada: Wietze Zijpp
el 5 de Abr. de 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.
0 comentarios
Respuesta aceptada
MJFcoNaN
el 5 de Abr. de 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 comentario
Más respuestas (0)
Ver también
Categorías
Más información sobre Linear Regression en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!