How do I summarize this code in a for-loop?

I am supposed find the best rational approximation for e using the quotient q/p, such that q is a 1-digit number, 2-digit number up to a 6-digit number. I've figured out how to solve the problem but I am certain I can make my code more efficient with a for loop. Any leads on how that would look like?
Some of the code:
a = 1:9; b = 10:99; c = 100:999; d = 1000:9999; e = 10000:99999; f = 100000:999999;
q = a; %set q eual to the first vector (1 digit)
p = round(q*exp(1)); %q is integer expression for e*q
T = p./q; %gather their quotient in vector T
best = T(1); %run sorting algorithm
for i = T
if abs(i-exp(1))<abs(best-exp(1))
best = i; %keep checking the next value for being a better approximation
end
end
x = find(T==best); tal1 = p(x)+"/"+q(x); %save tal1 as the quotient of the best approximation
%now repeat the process for b through f (2digit numbers to 6 digit numbers)

 採用された回答

the cyclist
the cyclist 2021 年 2 月 2 日
編集済み: the cyclist 2021 年 2 月 2 日

2 投票

for ne = 1:6 % Loop over the exponent
q = 10^(ne-1) : (10^ne-1);
p = round(q*exp(1)); %q is integer expression for e*q
T = p./q; %gather their quotient in vector T
best = T(1); %run sorting algorithm
for i = T
if abs(i-exp(1))<abs(best-exp(1))
best = i; %keep checking the next value for being a better approximation
end
end
x = find(T==best); tal1 = p(x)+"/"+q(x) %save tal1 as the quotient of the best approximation
end

1 件のコメント

Geeniee
Geeniee 2021 年 2 月 2 日
brilliant, thank you!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2021 年 2 月 2 日

コメント済み:

2021 年 2 月 2 日

Community Treasure Hunt

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

Start Hunting!

Translated by