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
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!