1
$\begingroup$

For example, I write a simple script in Mathematica like this: x = 4; y = 5; x*y. I want to get the output of x*y. I saved it as an .m file. But when I opened the file, it showed

(* ::Package:: *)
(* ::Input:: *)
(*x=4;y=5;x*y*)

Why there is (**)? If there is (**) in the code, the inner script will not run, right?

$\endgroup$
5
  • $\begingroup$ You need to use Code cells then. $\endgroup$
    – Kuba
    Commented Aug 13, 2021 at 9:51
  • $\begingroup$ Thanks Kuba. And how to Code cells? Could you write a simple example for me. I searched a lot on Google, but I can't find a suitable example for me. Thank you very much $\endgroup$
    – Yue Yu
    Commented Aug 13, 2021 at 10:08
  • $\begingroup$ It should be the default cell in .m files. If you use .nb then Alt+8 will create new / covert selected to code. $\endgroup$
    – Kuba
    Commented Aug 13, 2021 at 10:11
  • $\begingroup$ Thanks. I tried it. I used Alt+8, which created a gray cell. Then I copied the code in that cell and saved as .m file. The code in the gray cell will not covered with (**) $\endgroup$
    – Yue Yu
    Commented Aug 13, 2021 at 10:26
  • $\begingroup$ But there is still the default code like (* ::Package:: ) and ( :: Input:: Initialization:: *). I still do not understand it and how it works clearly. I need to read the help of mathematica. Thanks! $\endgroup$
    – Yue Yu
    Commented Aug 13, 2021 at 10:30

1 Answer 1

3
$\begingroup$

I assume you created a notebook, wrote something in it, then used File -> Save As... and chose "m. file"?

First of all, if you are looking for create a plain text Mathematica script (.m file or .wl file), it is best not to use notebooks at all. Create an .m file directly, and edit that.


That said, if you need to save a notebook as an .m file, only "initialization cells" will be included. Cells may be marked as "initialization cell" individually, or in groups. Check Cell -> Cell Properties. Some cell types, such as Code cells, have the "initialization cell" property by default. Input cells do not.

A simple way to add the initialization property to many cells at once is to place them under a Section heading (add a Section cell type above them), select the cell group, and add the "initialization group" property to it.

$\endgroup$
2
  • $\begingroup$ Yes, that is what I mean. And how to set a Section heading. It seems that there is no Section command. $\endgroup$
    – Yue Yu
    Commented Aug 13, 2021 at 12:20
  • $\begingroup$ @YueYu Format -> Style -> Section, after having placed the input cursor inbetween cells (not inside of a cell). Or use Alt-4 (Win/Linux) or Command-4 (Mac). $\endgroup$
    – Szabolcs
    Commented Aug 13, 2021 at 12:24

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.