3

n*log2(n) = A, with A a known value. How do I solve for n in Matlab? Note that n isn't necessary an integer.

nrz
  • 10,435
  • 4
  • 39
  • 71
zoey
  • 529
  • 1
  • 6
  • 14

4 Answers4

6

Or solve the equation analytically and use that:

n = A*log(2)/lambertw(A*log(2))
Gunther Struyf
  • 11,158
  • 2
  • 34
  • 58
  • My preference too, but of course this requires the symbolic toolbox. –  Sep 21 '12 at 14:02
  • 4
    I had to look. There is a lambertw tool on the FEX. http://www.mathworks.com/matlabcentral/fileexchange/3644-real-values-of-the-lambert-w-function –  Sep 21 '12 at 14:04
2

Not the most elegant solution, but you can use fmincon

n = fmincon(@(N) abs(N*log2(N)-A),10, [],[],[],[],1,Inf)
Rasman
  • 5,349
  • 1
  • 25
  • 38
2

Just use fzero:

solution = fzero(@(n) n.*log2(n)-A, A/5);

I found the initial guess empirically by examining the solution's behaviour on the interval 0-1000; you might want to adjust it for your use case.

Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96
1

If you have Symbolic Math Toolbox installed, all you need is:

solve('n*log2(n)=A', 'n')

ans =
    (A*log(2))/lambertw(0, A*log(2))

You can also use solve with syms:

syms n A

solve(n*log2(n)==A, n)

After syms n A you can also define the value of A:

A = 0
solve(n*log2(n)==A, n)

ans =
    1

A = 2
solve(n*log2(n)==A, n)

ans =
    2

A = 3
solve(n*log2(n)==A, n)

ans =
    (3*log(2))/lambertw(0, 3*log(2))
nrz
  • 10,435
  • 4
  • 39
  • 71