0
$\begingroup$

I wrote the following Matlab function:

function $s = Stirling(x,t)$

equation $$ \frac{(s^{(s+0.5)})}{(s-t)^{(s-t+0.5)}}=x.\times exp(t).\times t!$$

$s=$solve (eqn, $s$);

end

Now when I run the command $Stirling(18,3)$ for example, I expect to get a result like $5.7.$

Instead, I get the following error: Undefined function or variable "$s$".

Error in Stirling (line $2)$ eqn $$ \frac{(s^{(s+0.5)})}{(s-t)^{(s-t+0.5)}}=x\times exp(t)\times t!$$

Even when I change my code into:

function $s = Stirling(x,t)$

syms $i;$

eqn $$ \frac{(i^{(i+0.5)})}{(i-t)^{(i-t+0.5)}}=x \times exp(t)\times t!$$

s=solve (eqn, i);

end

And then I run the command Stirling(18,3), I still get the error: Error using solve (line 267) Specify a variable for which you solve.

Error in Stirling (line 4) s=solve (eqn, i);

Does anyone have any suggestions as to how I could force Matlab to recognize "s" as a declared variable?

  • 0
    You should try the examples on the solve documentation page.2017-01-13
  • 1
    You're doing the wrong thing anyway; this problem is too hard for solve (a *symbolic* solver) to handle. Use fsolve instead. In particular you can have the body of your function be just s=fsolve(@(r) r^(r+0.5)/((r-t)^(r-t+0.5))-x*exp(t)*factorial(t),2*t) (where I just picked 2*t more or less at random as a first guess, you may need to tune that).2017-01-13
  • 0
    2t is a good guess. I never knew fsolve existed before. Thank you so much.2017-01-13

1 Answers 1

0

You should define the symbol variable $s$ first, then you can solve it A example code like this may work

function s=stirling(x,t)
syms s
solve (s^(s+0.5)/(s-t)^(s-t+0.5)==x*exp(t)*factorial(t))
  • 0
    I run it , stirling(18,3) will give you a numerical result as 5.80845335777646912827419373369712017-01-13
  • 0
    plus, for the code problem, you better ask for programming and also post your original code then people can check your code.2017-01-13
  • 0
    Thanks. I gave you a rep but it didn't record it for some reason. Also, if I add semicolons at the end of each line, Matlab acts weird!2017-01-13
  • 0
    Yes, I noticed that problem. Do not know why.2017-01-14