Creating a function in MATLAB
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Saurabh Madankar
am 11 Feb. 2022
Kommentiert: Walter Roberson
am 11 Feb. 2022
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,
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/891385/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/891390/image.png)
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?
0 Kommentare
Akzeptierte Antwort
Walter Roberson
am 11 Feb. 2022
for I = 1 : 10
[J, K] = decode(I);
fprintf('i = %d, j = %d, k = %d\n', I, J, K);
end
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 Kommentare
Walter Roberson
am 11 Feb. 2022
j = floor(log2(i)) ;
k = i - 2.^j;
... a vectorized version
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!