Azzera filtri
Azzera filtri

How to use loop to fill in specific numbers?

4 visualizzazioni (ultimi 30 giorni)
Daniel Holden
Daniel Holden il 25 Mar 2024
Modificato: John D'Errico il 25 Mar 2024
I want to make a matrix that maps out all positive integer based fractions up to 4/8 as shown below.
I have done this in a laboriously manual way as can be seen below. I am quite certain this is not the best way nor the most efficient as I intend to make this table up with larger numbers. I have a vague idea of putting a loop in a loop, but this also seems convoluted. So any ideas or suggestions to make this as efficent as possible would be appreciated!
for i = 1:8
n_d(i,1) = 1;
n_d(i,2) = i;
end
for j = 9:16
n_d(j,1) = 2;
n_d(j,2) = j-8;
end
for k = 17:24
n_d(k,1) = 3;
n_d(k,2) = k-16;
end
for l = 25:32
n_d(l,1) = 4;
n_d(l,2) = l-24;
end
  2 Commenti
VBBV
VBBV il 25 Mar 2024
You can use if-else statements to make the code simpler with only one loop
for i = 1:32
if i>=1 & i<=8
n_d(i,1) = 1;
n_d(i,2) = i;
elseif i > 8 & i <= 16
n_d(i,1) = 2;
n_d(i,2) = i-8;
elseif i > 16 & i <= 24
n_d(i,1) = 3;
n_d(i,2) = i-16;
else
n_d(i,1) = 4;
n_d(i,2) = i-24;
end
end
disp(n_d)
1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 3 1 3 2 3 3 3 4 3 5 3 6 3 7 3 8 4 1 4 2 4 3 4 4 4 5 4 6 4 7 4 8
John D'Errico
John D'Errico il 25 Mar 2024
Modificato: John D'Errico il 25 Mar 2024
If these are indeed meant to represent "fractions", then do you want to have both the pairs {1,4} and {2,8} in there as separate items in the list? Of course, there are other examples too of fractions in your list that are not reduced.

Accedi per commentare.

Risposte (1)

Bruno Luong
Bruno Luong il 25 Mar 2024
Modificato: Bruno Luong il 25 Mar 2024
T = combinations(1:4,1:8)
T = 32x2 table
Var1 Var2 ____ ____ 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8
% for alder release that does not support combinations
[v1 v2] = meshgrid(1:4,1:8);
v1 = v1(:);
v2 = v2(:);
T = table(v1,v2)
T = 32x2 table
v1 v2 __ __ 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Prodotti


Release

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by