Creating a function in MATLAB

2 ビュー (過去 30 日間)
Saurabh Madankar
Saurabh Madankar 2022 年 2 月 11 日
コメント済み: Walter Roberson 2022 年 2 月 11 日
I need to create a function with input i and outputs j and k. So i varies from 1,2,3... and i,j and k are related as , where j =0,1,2,... and k=0,1,2,...,. So,
for input i=1, outputs should be j=0,k=0;
i=2 j=1,k=0;
i=3 j=1,k=1;
i=4 j=2,k=0;
i=5 j=2,k=1;
i=6 j=2,k=2;
i=7 j=2,k=3;
and so on. How do I create such a function?

採用された回答

Walter Roberson
Walter Roberson 2022 年 2 月 11 日
for I = 1 : 10
[J, K] = decode(I);
fprintf('i = %d, j = %d, k = %d\n', I, J, K);
end
i = 1, j = 0, k = 0 i = 2, j = 1, k = 0 i = 3, j = 1, k = 1 i = 4, j = 2, k = 0 i = 5, j = 2, k = 1 i = 6, j = 2, k = 2 i = 7, j = 2, k = 3 i = 8, j = 3, k = 0 i = 9, j = 3, k = 1 i = 10, j = 3, k = 2
function [j, k] = decode(i)
L2 = nextpow2(i);
if 2.^L2 == i
j = L2;
k = 0;
else
j = L2 - 1;
k = i - 2.^j;
end
end
  2 件のコメント
Saurabh Madankar
Saurabh Madankar 2022 年 2 月 11 日
編集済み: Saurabh Madankar 2022 年 2 月 11 日
Thanks a lot, I didn't know about the built in function nextpow2. I went through the documentation and now have understood how this code works.
Walter Roberson
Walter Roberson 2022 年 2 月 11 日
j = floor(log2(i)) ;
k = i - 2.^j;
... a vectorized version

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

その他の回答 (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