Creating a nested loop
조회 수: 2 (최근 30일)
이전 댓글 표시
Suppose I want to generate a 2 x 9 matrix by looping the following code twice
for j = 1:size(Mdl_vol,2)
EstMdl = estimate(Mdl_vol(j),IVOLI(:,1),'Display','off');
results = summarize(EstMdl);
AIC(j) = results.AIC;
BIC(j) = results.BIC;
end
I tried this;
for i = 3:4
for j = 1:size(Mdl_vol,2)
EstMdl = estimate(Mdl_vol(j),IVOLI(:,i),'Display','off');
results = summarize(EstMdl);
AIC(i,j) = results.AIC;
BIC(i,j) = results.BIC;
end
end
but it gives me a 4x9 matrix for some reason
댓글 수: 0
채택된 답변
Voss
2022년 4월 8일
The resulting matrices have 4 rows because i goes from 3 to 4 and you use i as the row index when building the matrices.
To have the 3rd and 4th columns of IVOLI correspond to rows 1 and 2 of AIC and BIC, you can do this:
n_col = size(Mdl_vol,2);
AIC = zeros(2,n_col); % initialize the matrices to the right size
BIC = zeros(2,n_col);
for i = 3:4
for j = 1:n_col
EstMdl = estimate(Mdl_vol(j),IVOLI(:,i),'Display','off');
results = summarize(EstMdl);
AIC(i-2,j) = results.AIC;
BIC(i-2,j) = results.BIC;
end
end
Or you can do this, which is more general:
I_col_idx = [3 4];
n_row = numel(I_col_idx);
n_col = size(Mdl_vol,2);
AIC = zeros(n_row,n_col); % initialize the matrices to the right size
BIC = zeros(n_row,n_col);
for i = 1:n_row
for j = 1:n_col
EstMdl = estimate(Mdl_vol(j),IVOLI(:,I_col_idx(i)),'Display','off');
results = summarize(EstMdl);
AIC(i,j) = results.AIC;
BIC(i,j) = results.BIC;
end
end
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!