1
$\begingroup$
ABCDSeries[x0_] = Module[{x=x0, s1, s2, s3, str, tmp},
s1 = "R";
s2 = "C";
s3 = "L";
str = StringTake[SymbolName[t], 1];
tmp = Which[str=="R", x, str=="C", 1/(I*W*x), str=="L", (I*W*x)];
tmp
];

Code Above is used for generate the impedence for circuit analysis

There are three types of input: Resistor R, Capacitor C and Inductor L

And the output of function is R, 1/(I W C) and I W L, respectively.

The line str = StringTake[SymbolName[t], 1]; is used so as if we input Ls,

then the function will output I W Ls.

However, I type ABCDSeries[Ls] and receive x, not I W Ls.

I have no idea how to fix it. I think maybe the problem is related to local variable

How can I solve the problem, thanks for your help

$\endgroup$
4
  • $\begingroup$ Greetings! Make the most of Mma.SE and take the tour now. Help us to help you, write an excellent question. Edit if improvable, show due diligence, give brief context, include minimal working examples of code and data in formatted form. As you receive give back, vote and answer questions, keep the site useful, be kind, correct mistakes and share what you have learned. $\endgroup$
    – rhermans
    Commented Feb 22, 2016 at 10:31
  • 1
    $\begingroup$ Define your function with a := instead of a =. Also, when you define str it refers to some variable t - if you change that to x or x0 it works better. $\endgroup$
    – Jason B.
    Commented Feb 22, 2016 at 10:36
  • 1
    $\begingroup$ But one more thing, if Ls is defined to be a number instead of just a symbol, you will get an error. $\endgroup$
    – Jason B.
    Commented Feb 22, 2016 at 10:38
  • $\begingroup$ I've done some changes (j->I, w->W, ab ->a b) in your question. $\endgroup$
    – Kuba
    Commented Feb 22, 2016 at 10:48

1 Answer 1

3
$\begingroup$
ClearAll[ABCDSeries];
ABCDSeries[x0_Symbol] := Module[{ str},
   str = StringTake[SymbolName[x0], 1];
   Switch[str,
    "R", x0,
    "C", 1/(I*W*x0),
    "L", (I*W*x0)
    ]
];


ABCDSeries[Ls]
i Ls W

I put there x0_Symbol since SymbolName is not HoldFirst, if you need to have this function working for Ls where Ls may have a value, then SetAttributes HoldFirst to your function and change to SymbolName @ Unevaluated @ x0.

Search documentation for references to those things to understand what is going on. Moreover, what you need to read about:

$\endgroup$
1
  • $\begingroup$ Note also that Kuba has removed unnecessary temporary variables and used Switch rather than Which. These are nice enhancements to your original code. $\endgroup$ Commented Feb 22, 2016 at 14:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.