This is my day one using Mathematica. What I’m trying to do now is to translate a piece of my Matlab code into Mathematica. Here is an MWE, where I defined a module called coeffs:
coeffs[n0_] := Module[{n = n0},
c = Table[0, {i, n + 1}, {j, n + 1}]
Do[c[[l + 1, 2]] = 20 , {l, 0, n}]];
I’m trying to use this module as a function in usual sense, which takes a scalar number as input, create an empty matrix, and change the entries in the second column to something else. However, calling this function by coeffs[2] gives a result of {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}.
It seems no entries in the second column has been changed. What’s the error in my code? Thanks!!
Inside a module you need to put ; between your expressions. To create a so-called CompoundExpression
ClearAll[coeffs]
coeffs[n0_] := Module[{n = n0, c},
c = Table[0, {i, n + 1}, {j, n + 1}];
Do[
c[[l + 1, 2]] = 20
,
{l, 0, n}
];
c
];
Moreover, it is a good idea to make c a local variable, finally you need to return something. That can be done by just putting c at the end (without semicolon). Or explicitly do so using Return.
Thank you very much!! I see. In fact, the code I posted is just a minimal working example, every single entry in a column will be assigned a different value, not always 20. But thanks for tricks. They’ll be very useful!
One more quick question - to define a “function” in usual sense, shall I use Module or Block? What’s the difference?
There are entire topics on it and the differences are subtle:
Let’s just say that generally you will use Module (or With if you have constants rather than variables) . But sometimes Block can be handy (and slightly faster) and can be used in nifty ways. Since you are a beginner, don’t worry too much for now… If you really want to know, i recommend you to read the aforementioned topic, it explains it in a lot of detail!
_ is called a Blank, and can be read as ‘something’… so what the rule says: at position something comma 2 put value 20. where something can be any value, i.e. it describes a column.
i_
this can be read as “something that I will call i” such that you can do things like:
SparseArray[{i_, 2} -> i^2, {5, 5}]
it will plug in 1,4,9,16,25.
Read also the introduction to Wolfram Language:
Note that patterns (these things with _ and so on) is at chapter 32, so it is reasonably advanced…