2
$\begingroup$

I've written a function that should try to simulate a "triangle-wave-signal", given a few parameters. It looks like this:

tria[p_, s_, t_, ts_] := (
Module[{pps = s/(2 p), z = 0, cs = 0, cpos = 0, spp = 2/(s/(2 p)), 
ct = 0, ret = {}},
  For[i = 0, i < 2 p, i++, 
    For[j = 0, j < pps, j++,
      AppendTo[ret, {ct, cs}];
      ct = ct + ts;
      cpos += 1;
      spp *= If[TrueQ[cpos == s/(2 p)], cpos = 0; -1, 1, 1];
      cs += spp;
    ];
  ]; ret
 ]
)

Most of it is unimportant, but here is the line that doesn't work:

spp *= If[TrueQ[cpos == s/(2 p)], cpos = 0; -1, 1, 1];

I don't know if I'm right, but I have a feeling that the If-Statement simply doesn't do anything. I can also write it in a way that the multiplication happens inside the statement, but still, nothing changes. Weirdly, if I execute this If-Statement alone (Outside of the function), it works... What am I missing here? Why isn't it working like it should?

$\endgroup$
3
  • $\begingroup$ Remove the TrueQ part. The expression cpos == s/(2 p) will evaluate to True or False when numbers are plugged in already. $\endgroup$
    – march
    Commented Jan 21, 2016 at 18:18
  • 1
    $\begingroup$ By the way, you can check to see if that expression is doing anything by wrapping the expression cpos == s/(2 p) ins Sow Sow[cpos == s/(2 p)] and when you run the function using Reap: Reap@tria[1, 4, 2, 1] will return a list: the first element is the output of the function and the second element is a list of the instances of the Sowed expression. In this case, it clearly is doing something. Reap-Sow is nice for debugging, among many other things. By the way, what makes you think it's not doing anything? $\endgroup$
    – march
    Commented Jan 21, 2016 at 18:24
  • $\begingroup$ @march Weird, last time I tried removing the TrueQ it didn't work... Now it does. Thanks a lot! Now I just have to fix it so it ranges from -1 to 1 instead of 0 to 2, but that should be easy enough. $\endgroup$ Commented Jan 21, 2016 at 18:36

1 Answer 1

1
$\begingroup$
a = 3;
b = 2;
c = 4;

Plot[a TriangleWave[b x + c], {x, 0, 10}]
$\endgroup$
2
  • $\begingroup$ This is nice, but I need to be able to control the amount of dots I have while also controlling the horizontal axis... I hope what I just said makes sense, I somehow feel like it doesnt. $\endgroup$ Commented Jan 21, 2016 at 18:31
  • $\begingroup$ I don't understand what you mean by "amount of dots." The amplitude, period and phase of the triangle wave are governed by a, b and c in my code. $\endgroup$ Commented Jan 21, 2016 at 18:50

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.