How to Copy and Paste into a MATLAB Script

By Jim Sizemore, John Paul Mueller

Experimentation is an essential part of working with MATLAB. After you get a particular command just right, you may want to add it to a script. This act involves cutting and pasting the information. When working in the Command window, simply highlight the text you want to move into a script, right-click it, and choose Copy or Cut from the context menu.

As an alternative, most platforms support speed keys for cutting and pasting, such as Ctrl+C for copy and Ctrl+X for Cut.

Copying and cutting places a copy of the material on the Clipboard. Select the Editor window, right-click the location where you want to insert the material, and choose Paste from the context menu. (The pasted material is always put wherever the mouse pointer is pointing, so make sure you have the mouse cursor in the right place before you right click.)

As an alternative, most platforms provide a speed key for pasting, such as Ctrl+V. In this case, you place the insertion pointer (the text pointer) where you want the new material to appear.

The Command History window succinctly stores all the commands that you type, making it easy for you to pick and choose the commands you want to place in a script. The following list provides techniques that you can use in the Command History window:

  • Click a single line to use just that command.

  • Ctrl+Click to add additional lines to a single line selection.

  • Shift+Click to add all the lines between the current line and the line you clicked to a single line selection.

The result is that you end up with one or more selected lines. You can cut or copy these lines to the Clipboard and then paste them into the Editor window.

Using other sources for script material is possible, and you should use them whenever you can. For example, when you ask for help from MATLAB, the help information sometimes includes example code that you can copy and paste into your script. You can also find online sources of scripts that you can copy and paste.

Checking the results of the pasting process is important in this case to ensure that you didn’t inadvertently copy nonscript material. Simply delete the unwanted material before you save the script.