Matlab Tutorial 1: Hello world, plotting, mathematical functions and file types


Matlab M-files

Let’s now illustrate how to create an m-file (macro) or if you prefer a small program. Assume that we have to make a number of command lines before we end up with a plot in a figure window. If we make an error in the command line then we have to repeat the command line sequence. A better way should be to put the command line sequence in an m-file and just correct the bad command line there. Execute the m-file simply by writing the name of the m-file in the command window and without the extension .m. In order to let Matlab find the m-file give the path or make the directory where you have stored the m-file to your current directory.

Exercise 3: Creating m-files in Matlab

Open an edit window where we can write the command lines. Click on the white sheet in the menu under File or simply write edit in the command window. Alternatively File->New ->M-file. The following is written in the edit window:

>> A(2,1)+A(1,3)+A(2,3)

Everything that follows the %-character on the same line is regarded a comment and ignored. Also note the semicolon. It prevents output from a command to be printed out in the command window. If the command is a calculation, it is still executed. Save the m-file as exercise3.m in directory work. Run the m-file by writing exercise3 in the command window followed by <enter>. The result should be the same that as in the figure below.

Sine function plot

Sine function plot

Styling of Matlab Plots

Note that title, xlabel, ylabel and legend could have been performed in the figure window, in the menu under Insert. It looks a bit odd that both curves have the same line styles. This could well be a problem if we did have a problem with trigonometric functions. We will try to solve this. Click on the arrow in the menu of the figure window. Then double click on any of the curves. Enter under Style->LineStyle and change to dotted line. You can also change the color if you want (Line Color).

There is also a possibility to exclude or exchange values in the plot. Let’s illustrate how this is done. Double click on any curve and choose Data->YData->y1 and then Edit Data. Now all plotting values that are used for one of the sine curves are accessible. Change the values to 2 for all indexes from 10 to 20. Take a new look on the plot. This is perhaps not normal procedure in dealing with data, but I am just showing the possibilities with different tools.

Pages: 1 2 3 4 5