How to use loop to fill in specific numbers?
1 回表示 (過去 30 日間)
古いコメントを表示
I want to make a matrix that maps out all positive integer based fractions up to 4/8 as shown below.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1650801/image.png)
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
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)
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
2024 年 3 月 25 日
編集済み: Bruno Luong
2024 年 3 月 25 日
T = combinations(1:4,1:8)
% for alder release that does not support combinations
[v1 v2] = meshgrid(1:4,1:8);
v1 = v1(:);
v2 = v2(:);
T = table(v1,v2)
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!