フィルターのクリア

how to find the nearest smallest power of 2 to an integer?

46 ビュー (過去 30 日間)
Mnr
Mnr 2015 年 5 月 5 日
コメント済み: Mnr 2015 年 5 月 5 日
Hello all,
I would like to write a code that finds the nearest smallest power of 2 to integers. For instance, if my integer is 6, its smallest nearest power of 2 is 4, while if the integer is 12, the smallest nearest integer is 8. I would appreciate if somebody can help me please. Thanks.

採用された回答

Stephen23
Stephen23 2015 年 5 月 5 日
編集済み: Stephen23 2015 年 5 月 5 日
>> N = 6;
>> pow2(floor(log2(N)))
ans =
4
And it is even fully vectorized code, so you can check all of your values at once:
>> pow2(floor(log2([6,12])))
ans =
4 8
  3 件のコメント
Stephen23
Stephen23 2015 年 5 月 5 日
編集済み: Stephen23 2015 年 5 月 5 日
Option Two (more robust):
[X,~] = log2(N);
if X==0.5
... code
else
... other code
end
Option Two (one line):
if rem(log2(N),1)==0
... code
else
... other code
end
Mnr
Mnr 2015 年 5 月 5 日
Thanks a lot!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

タグが未入力です。

Community Treasure Hunt

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

Start Hunting!

Translated by