Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Mathematica: Module inside For loop

  1. Jan 11, 2012 #1

    ChristinaJ

    User Avatar
    Gold Member

    Hi all,

    I have the following code which runs without error but gives no output. It's probably simple but I just can't see the problem.

    LM={};

    M[line_, cur_, lq_, ld_, k_] := For [i = 1, Length[line[[1]]], i++,
    Module[{m}, If[line[[1, i]] == "Q",
    m = {{Cos[k*Sqrt[Abs[cur]]*lq], Sin[k*Sqrt[Abs[cur]]*lq]/(
    k*Sqrt[Abs[cur]])}, {-k*Sqrt[Abs[cur]]*
    Sin[k*Sqrt[Abs[cur]]*lq], Cos[k*Sqrt[Abs[cur]]*lq]}}.{{1,
    ld}, {0, 1}},
    m = {{1, ld}, {0, 1}}];
    AppendTo[LM, m]]];

    M[line, line[[3]], line[[4]], line[[5]], 1.8]


    Where Dimensions[line]={5,15} the first 2 rows of which are strings and the remainder numbers.

    For LM I get LM={}

    Any help very much appreciated.

    Christina
     
  2. jcsd
  3. Jan 11, 2012 #2

    CompuChip

    User Avatar
    Science Advisor
    Homework Helper

    Maybe you need to re-assign the result to the list:
    Code (Text):
    LM = Append[LM, m]
    (If this solves the problem, don't feel bad... you don't want to know how many hours I spent looking for similar mistakes)

    Also, if the whole body of your module is a single If-statement, what do you need the module for?
    You can just as well write
    Code (Text):

    For[..., ..., LM = Append[LM, If[...]]]
     
    instead of
    Code (Text):

    For[..., ..., Module[m = If[...]; LM = Append[LM, m]]
     
     
  4. Jan 11, 2012 #3

    ChristinaJ

    User Avatar
    Gold Member

    Thanks CompuChip,

    You were right; using Module was unnecessary.

    The actual problem turned out to be a foolishly simple mistake. I had assigned the end value for i in the loop in an incorrect way.

    Doh!
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook