Conditional loop to loop until result is an integer.
显示 更早的评论
I am trying to create a script that will give me the value for an integer 'n' such that 2n/k = a where a is also an integer. K varies from 0.01 to 1 in increments of 0.01. I am then using this result to find delta where delta = 2*pi*n. The first few results are correct when verified with a calculator. The 6th and 7th gives results 9 and 77 as the lowest value for n for k=0.06 and 0.07 where a is an integer however from a calculator it can be seen that the values 3 and 7 for n would also return an integer. For k=0.12 the script cannot find a value for n and runs infinitely despite the fact that n=3 would an integer value for a (2*3/0.12 = 50)
Currently I have
k(1)=0.01;
n(1)=1;
for i=1:100;
a(i)=(2*n(i))/k(i);
while floor(a(i))~=ceil(a(i))
n(i)=n(i)+1;
a(i)=(2*n(i))/k(i);
end
deltamax(i)=2*pi*n(i);
k(i+1)=k(i)+0.01;
n(i+1)=1;
end
采纳的回答
更多回答(1 个)
If 2n/k = a and you want to find n and a, rewrite this as 2n/a = k. So you want to return two integer matrices whose ratio is "close to" k. There is a function in MATLAB for this: rat.
[N, D] = rat(0.06)
Since N is odd, we cannot find n from it (N = 2*n.) If we let a = 2*D, then n is the same as N. (2*n)/a = (2*N)/(2*D) = N/D = k.
n = N
a = 2*D
[2*n/a; 0.06]
(2*n/a)-0.06 % small or zero
rat accepts a tolerance and if you do not provide one uses one that should probably be sufficient for the problems you've described.
类别
在 帮助中心 和 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!