Creating a nested loop

3 Ansichten (letzte 30 Tage)
Wietze Zijpp
Wietze Zijpp am 8 Apr. 2022
Beantwortet: Voss am 8 Apr. 2022
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

Akzeptierte Antwort

Voss
Voss am 8 Apr. 2022
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

Weitere Antworten (0)

Kategorien

Mehr zu Link-Level Simulation finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by