How to use loop to fill in specific numbers?

3 ビュー (過去 30 日間)
Daniel Holden
Daniel Holden 2024 年 3 月 25 日
編集済み: John D'Errico 2024 年 3 月 25 日
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 Center および File ExchangeLoops 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