Message Boards Message Boards

0
|
5571 Views
|
2 Replies
|
0 Total Likes
View groups...
Share
Share this post:

Emulate MatLab functions using Wolfram language?

Posted 5 years ago

So, I'm attempting to emulate MatLab functions in Mathematica (mainly for practice in programming) and I have run across a very peculiar error where If doesn't simplify down to the False portion of the function:

Trapz[xlist_: Null, ylist_] := Block[
{lxlist, rxlist, lylist, rylist, ylen, i, k, A, B = {}, listx},
If[Length[Dimensions[ylist]] == 1,

rxlist = 
Prepend[If[xlist == Null, Table[i, {i, 1, Length[ylist]}], xlist],
0];
lxlist = 
Append[If[xlist == Null, Table[i, {i, 1, Length[ylist]}], xlist], 
0];
lylist = Prepend[ylist, 0];
rylist = Append[ylist, 0];
    Delete[
If[xlist == Null, Table[1, {i, 1, Length[ylist]}], 
rxlist - lxlist], {{1}, {-1}}].
    Delete[(lylist + rylist)/2, {{1}, {-1}}]
,
ylen = Length[ylist];

If[xlist == Null, listx = Table[1, {i, 1, Length[ylist[[1]]]}],
listx = xlist]; (*Error begins here and continues onward*)

    For[i = 1, i <= ylen, i++,
lxlist = Prepend[listx, 0];
rxlist = Append[listx, 0];
lylist = Prepend[ylist[[i]], 0];
rylist = Append[ylist[[i]], 0];
For[i = 1, i <= ylen, i++, A = Append[B, ylist[[i]].listx]; 
B = A]; B
]]]

After evaluating this code:

Trapz[Table[i, {i, 0, 5}], Table[i^2, {i, 0, 5}]]

I receive this:

If[{1, 1, 1, 1, 1, 1}].{1/2, 5/2, 13/2, 25/2, 41/2}

And an error that sta

Attachments:
POSTED BY: Joshua Champion
2 Replies
Posted 5 years ago

Hi Joshua,

At least one issue with the code is the If condition xlist == Null. It will remain unevaluated unless xlist is Null. So the If will remain unevaluated.

{0, 1, 2, 3, 4, 5} == Null
(* {0, 1, 2, 3, 4, 5} == Null *)

If[{0, 1, 2, 3, 4, 5} == Null, True, False]
(* If[{0, 1, 2, 3, 4, 5} == Null, True, False] *)

Rather than testing for Null, test the Length of the list.

POSTED BY: Rohit Namjoshi

Joshua,

Use SameQ (===) instead of Equal in If. Mathematica can always tell if two items are not the same but Equal is more difficult (read the documentation — it describes this in detail). For example, q is not the same as y but they might be Equal.

Regards

Neil

POSTED BY: Neil Singer
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract