How to use loop to fill in specific numbers?

3 次查看(过去 30 天)
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 个评论
VBBV
VBBV 2024-3-25
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 2024-3-25
编辑:John D'Errico 2024-3-25
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.

请先登录,再进行评论。

回答(1 个)

Bruno Luong
Bruno Luong 2024-3-25
编辑:Bruno Luong 2024-3-25
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

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by