Generating a design matrix with for loops

2 vues (au cours des 30 derniers jours)
Anders Larsen
Anders Larsen le 22 Sep 2021
Hello everyone, I am trying to create a design matrix for simulation puposes using for loops with vectors, but I am struggeling with what to write in the inner most loop. The numbers are arbitrary, to get the hang of it, I need to be able to scale it up for vectors with 100 values or more.
The code looks as follows:
a = (1: 3)';
b = (4: 6)';
c = (7: 9)';
for i = a
for j = b
for k = c
e(i, j k)=...
end
end
end
The result should be a matrix with all posibilities of combinations of the 3 vectors and should look like:
e = 1 4 7
1 4 8
1 4 9
1 5 7
1 5 8
1 5 9
1 6 7
1 6 8
1 6 9
2 4 7...
Hope you guys can help, thanks!

Réponses (1)

Yongjian Feng
Yongjian Feng le 22 Sep 2021
Something like this?
a = (1: 3);
b = (4: 6);
c = (7: 9);
idx = 1;
for i = a
for j = b
for k = c
e(idx, 1) = i;
e(idx, 2) = j;
e(idx, 3) = k;
idx = idx + 1;
end
end
end
e

Catégories

En savoir plus sur Get Started with Optimization Toolbox dans Help Center et File Exchange

Produits


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by