Group Abstract Group Abstract

Message Boards Message Boards

0
|
12.8K Views
|
8 Replies
|
0 Total Likes
View groups...
Share
Share this post:

Create a function/method and return a matrix as a result?

Posted 9 years ago
POSTED BY: K X
8 Replies
Posted 9 years ago
coeffs[n0_] := SparseArray[{i_, 2} -> 20, {n0 + 1, n0 + 1}]
POSTED BY: Michael Helmle
Posted 9 years ago

Thanks. A dumb question - what does the underscore _ after i mean? Why i_, not just i?

POSTED BY: K X
POSTED BY: Sander Huisman
Posted 9 years ago

Thanks very much for the pointers. They're most helpful!

POSTED BY: K X

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.

POSTED BY: Sander Huisman

Side note:

   c = Table[0, {i, n + 1}, {j, n + 1}];

can be replaced by:

   c = ConstantArray[0, {n + 1,n + 1}];

which is similar to the function ones/zeros in Matlab but can be any value, including symbols, strings or ...

You can set all the values at once:

c[[1 ;; n+1, 2]] = 20

or even simpler:

c[[All, 2]] = 20
POSTED BY: Sander Huisman
Posted 9 years ago

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?

Again, thanks a lot!

POSTED BY: K X

There are entire topics on it and the differences are subtle:

http://community.wolfram.com/groups/-/m/t/1017668

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!

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