Day 02

Matlab scripts and functions

Attention! Outdated html version! Please use the pdf or docx version!

Command reference: Matlab syntax

pdf version of the script: [Tag02.pdf]

Word version of the script: [Tag02.docx]

Downloads:

T2C7) [large_matrix.mat]

T2H2) [complicated.m]

T2H3) [ueberraschung.mat]

new task (see pdf): [WetterBremen2014.mat]and [WetterHamburg.rdata]

All downloads at once: [downloads_Tag02.zip]

HTML version:

A) MATLAB SCRIPTS:

For complex calculations, it would be far too much work to type all work steps individually into the command window each time. This is why it is possible to write scripts - sequences of commands that are always executed in the same way. (Some of you already used this option yesterday.) A script is the implemented version of an algorithm.

  • If you have saved the script under a specific file name with the extension .m (the Matlab editor adds this extension automatically), you have created a new Matlab command .
  • If you call this command by typing it (without .m) into the Command Window, all lines of the file are processed one after the other. The next command can only be entered in the Command Window once all the lines have been processed.
  • Of course, the new command can also be used within another script (or function).

Used to structure larger programmes:

  • Subroutines, where parts of the programme are outsourced to separate files, which are then called from the main programme. This is particularly useful if certain subtasks have to be completed several times or could also be of interest in a different context.
  • Within a programme, so-called "cells" - programme parts - can be used to further subdivide the process. These can be easily found again in the programme and possibly used again elsewhere.

If you have not already done so, now is the right time to take a look at the texts Important concepts in Matlab and Important steps in programming, the content of which will not be repeated here.

To ensure that you and other people can still understand the Matlab programmes you have written after some time, you should get into the habit of using a "good style":

  • give the file a meaningful name
  • use meaningful variable names
  • comment generously (preferably every line that is not totally obvious)
  • provide the programme with a help text.
  • Matlab does not deal well with umlauts, spaces and arithmetic signs in file names. Therefore, only use file names (including directory names) with the normal letters of the alphabet (case sensitive) and underscores.

The Matlab editor is more than just a window for typing and saving commands. It contains a range of tools that make programming and, in particular, finding errors in programmes ("debugging") easier. Later in the course we will also use the Profiler. This tool provides information on how to make your programme more efficient in terms of computing time and memory.

One request: Please remember to use unique file names for your submitted solutions to the tasks marked in red by including your own name. Then save the tasks in the cloud system in your personal folder.

Tasks:

T2A1) If you did not create a directory for the data from this course on your laptop or under your university account on the university computers yesterday, do so now. It is a good idea to create further subfolders for the individual days.
In future, every time you restart Matlab, make sure that you are in the correct directory.

T2A2) Open the Matlab editor by clicking on the symbol for a new document. And type (or copy) there:

clear all
A1=ones(2,5);
A2=2*ones(2,5);

Asum=A1+A2;

  • Save this script as script.m (under File->save as). Make sure that you are in the correct directory.
  • Call the programme in the Command Window by selecting script in the Command Window.
  • What happens in the workspace?
  • Now delete the semicolon in each line of your script, save it and run it again. What is the difference?

T2A3) A script accesses the variables in the workspace directly and can change them. It therefore behaves as if you enter each command individually in the command window. Try entering them in the Command Window:

clear all % deletes all variables in the workspace
A1=[1 1; 2 2] % defines a new variable
script % calls the script defined above

Check which variables are now present in the workspace. What is the value of variable A1?

T2A4) When programming, it is very important to write comments in the programme so that you still know what you were thinking a few years later. Add a comment after each line of the programme, separated by %, to indicate what is currently happening, e.g.

clear all % delete all variables from the workspace

T2A5) In addition to the comments for the individual lines, each programme should have a comment header. Write a help text for skriptchen.m by adding a first line (starting with %) that states the name of the script and explains its content, e.g.

% skriptchen.m is an example script in which two specified matrices are added.

T2A6) This first line (or all first lines beginning with %) serve as help text for the respective script: Type help scriptchen in the Command Window.

T2A7) In our script, everything happens too quickly to be able to see the processing of the individual steps.

  • After each line of the script, add the line pause- This pauses the script during execution until you press any key.
  • Try this out and display a few lines on the screen "on the go". You can do this with the command disp('here is text').
  • The command pause command can also be used to view the programme execution in automatic slow motion, so to speak. If you pass it a number (e.g. with pause(2)), further programme execution is interrupted for a corresponding number of seconds.

T2A8) Instead of typing pause each time, you can also let the Matlab editor do the work for you. The editor offers the option of using the so-called cell mode. This means that programmes are built up from sub-blocks (cells).

  • Such a block is defined in the Matlab editor by a comment line beginning with %%. This should describe what happens in the next subsection of the programme.
  • The cell mode is particularly helpful for large programmes, as the blocks make it easy to understand the rough structure of the overall programme and blocks can be easily found and transferred to other programmes.
  • If you use "cells", you can also run them individually. To do this, click in the program code or the comment line of a "cell", which is then highlighted in colour.
  • At the top left there is an icon (two boxes with an arrow pointing to the top one) that only allows the relevant part of the programme to be executed.
  • Try this out by dividing your script into two parts, each beginning with a %% comment line.

T2A9) The Matlab editor can also be used for "debugging", i.e. to find errors. Even if there are no errors in the programme, debugging offers the possibility of "watching" Matlab at work and tracing the development of variable values step by step. Try out these possibilities:

  • If you click on the icon with the green arrow at the top of the editor bar, the script will start running.
  • If you do not want the entire programme to run, but want to check the status of the workspace in between, you can set so-called"breakpoints" at which the programme sequence is interrupted. You can do this by clicking on the small line in front of the line whose effect you want to see. This then becomes a red dot. Click again to make it disappear again.
  • Try out what happens if you set a breakpoint and let the script run. Test what you can and cannot do during this interruption in the Matlab Command Window. What happens if you click on the various arrow icons at the top of the editor in this state? In particular, how do you get out of debugging mode?
  • Instead of using the pause command, use the Matlab editor to view the processing of each step of the programme. Find out how to do this.

T2A10) Write a script spaghettiskript to solve the following task:

What you are looking for is the total length of the spaghetti on your dinner plate when it is lined up straight lengthwise.
You know that the spaghetti (without sauce) weighs 250g, has a diameter of 2mm when cooked and a specific weight of 1.05g/cm^3.
(If you are too stupid to deal with spaghetti, imagine that it is the total length of the DNA in a cell nucleus, which can in principle be calculated accordingly).

  • Think about the calculation method (if in doubt, use Wikipedia).
  • Implement this step by step in the lines of your script, using meaningful variable names and making sure that the units match!
  • Test your script by running it.
  • If the script does not deliver the expected result, you can use the debugging functions of the editor to find the error.

B) FUNCTIONS

You often do not want a script to be able to change any variables in the workspace because you want to continue using them. This is why there are functions:

  • A function is a programme that creates its own workspace during its execution, which is separated from the main workspace of the command window. This function workspace is deleted again once all programme lines have been processed.
  • Arguments are used for communication between the workspace of the command window and the workspace of the function:
  • Input arguments transfer variables from the workspace to the function so that they can be used there.
  • Output arguments transfer results of the function to the workspace.
  • All other variables used within the function are deleted as soon as the function is finished.

To create a function, the keyword function must appear in the first line of the file ("header"). The syntax for creating a function is the same as for calling a function, except for this keyword:

  • Creation (first line in the file):
  • function [output1,output2] = function name (input1, input2)
  • Call (in the command window):
  • [output1,output2] = function name (input1, input2)
  • Here are Output1, Output2, input1 and input2 are variable names (they could also be called A, TTT or Erna ).
  • The variables may have different names in the workspace of the function and in the workspace of the command window, but the values of the corresponding parameters are the same.
  • For example, if the call is:[a,b]=function name(27,M)
  • Then the variable input1 in the function has the value 27 and the variable input2 in the function has the same value as the variable M in the command window.
  • The function calculates values for the output arguments Output1 and output2 and passes these to the variables a and bwhich are contained in the workspace of the command window at the end of the function.

Good style:

  • Always use the same name for the file that you use in the function header.
  • Intercept "nonsensical" input parameters by querying them. (We will discuss how to do this tomorrow).
  • Consider BEFORE you write a programme whether a function or a script is the better choice and whether you want to outsource certain parts of the programme to a sub-function or a sub-script.

Tasks:

T2B1) We have already seen examples of predefined functions with input and output arguments yesterday, e.g.y=sin(x)or r=rem(a,b).

There are also functions that can have a variable number of input and output arguments:

  • Yesterday we already saw the function size function, which returns the size of a matrix.
  • size needs at least one matrix as input (size(M))
  • the dimension can also be specified (size(M,d)).
  • Depending on the input, either the number of rows and columns of the matrix is returned ([rows,columns]=size(M)) or only the size of one dimension (z=size(M,1)).
  • Try out what size returns for the different types of call when applied to a scalar, a vector and a 3x3 matrix.
  • For vectors there is the command length=length(a). What returns length(M) for a matrix M?

T2B2) Now for self-written functions:

  • Copy the content of spaghettiskript.m with the editor into a new file and add function spaghettifunction as the first line, before the help text. Save the file as spaghettifunction.m (conveniently, the Matlab editor will offer this as a standard option anyway).
  • Leave spaghetti function run. What happens?
  • Delete all variables of the workspace and run the function again. What happens?
  • Compare the behaviour of the function with that of the script. Does the function also behave as if the individual commands were entered in the command window?
  • As in T2B2), define a variable in the workspace of the command window as [1 1; 2 2]which has the same name as a variable in your spaghetti function. Then leave spaghetti function run. What happens? What is the value of the variable in the workspace of the command window when the function has run?
  • Set a breakpoint in the first line of your function and start the function in debugging mode. Take a look at how the workspace of the function changes from step to step as the programme is processed.

(Note: We will now change the function step by step. If you want to cancel all versions, you must use a new function name for saving and calling, e.g. spaghettiskriptC2. Remember to update the help text for this and the next steps).

T2B3) You often want a function to return a result that can be used further. This is achieved by an output argument.

  • Add it to the first line:
  • function laenge=spaghetti function
  • Delete all variables in the workspace and call spaghetti function function. What happens?
  • You may want to continue using the result of your function. To do this, assign its output value to a new variable, e.g. by calling spaghetti length=spaghetti function for example.

T2B4) It is well known that the amount of spaghetti on cafeteria satellites varies considerably depending on the personality and mood of the cafeteria staff. We take this into account by adding an input argument to the first line:
function laenge=spaghettifunktion(gewicht)
and use the variable gewicht for your calculation. (Alternatively, if you have already chosen a different name for the weight in your function, you can write this variable name in the brackets of the first line).

  • To test, call the function with length=spaghetti function(250). Does the result meet your expectations? Calculate the lengths for a few other weights.
  • What happens if you now call the spaghetti function without an input or output argument?
  • Try to trick your spaghetti function by giving it "unsuitable" input values, e.g. a matrix. What works? When do you get error messages?

T2B5) Unfortunately for us, not only the amount of spaghetti on the plate varies, but also its consistency. When they are completely overcooked, they have a specific weight that does not deviate significantly from water, e.g. 1.01g/cm^3.

  • To include the specific weight in the programme, we need several input arguments.
  • Add the specific weight as an additional input argument and use it in the calculation. The list of input arguments (both in the programme text and in the call) is separated by commas in the brackets after the function name.
  • Test your new function.

T2B6) In order to demonstrate the variability of spaghetti quality, think of laying a line of spaghetti tables from the Wechloy canteen to the main canteen (0.9km).

  • Therefore, add the number of spaghetti portions you need for this distance as a further output argument. The output arguments are placed in square brackets before the equals sign and the function name.
  • Test your new function.
  • *) As you cannot buy fractions of portions of spaghetti in the canteen, please round the portions to the nearest larger whole number. Please refer to the help to find out which function you can use.

T2B7) Try out how the debugging mode of the editor behaves when it is applied to a function with input and output parameters. What are the differences to using it with a script? What do you have to consider?

C) SAVING AND LOADING DATA:

Normally, Matlab is not operated by typing in all the data that you want to process, but by using files from which data is read in and saved in the data.

  • When saving a file with the command save filename Matlab saves its workspace (i.e. all current variables) to the data carrier by default.
  • The automatically generated extension of the file name is .mat
  • If you only want to save part of the current variables, you must specify this specifically (see T2C3).

When reading in a .mat file with the command load filename, Matlab creates the variables stored in it in its workspace.

  • Note: The variables read in have the same names that they had before they were saved (and not the file name). If variables with the same name exist in the workspace, they will be overwritten!
  • It does not matter whether when reading in only file name orfilename.mat is specified

Note: Matlab uses the current directory specified in the Current Directory bar at the top for saving and loading.

  • You can change the directory by navigating to theCurrent Folder window by clicking on the correct position in the directory tree.
  • A frequently faster option is to specify the path via the command line.
  • The command for changing the directory iscd. For example cd Tag1 "change to the subfolder Tag1".
  • To change a directory upwards, use the designation .. so you can use the command cd ../Tag2 for example, you can change from a subfolder Tag1 directly to another subfolder Tag2.
  • The direct specification of the directory is particularly useful if you want to load or save a file in a directory other than the current one. For example save Tag1/testfile means that the current workspace is saved in the subdirectory Tag1 under the name testdatei.mat.

Matlab images are saved in a slightly different way and reopened in Matlab as data.

  • The easiest way to save mappings is to use the menu item >File >Save as.
  • The default is then that the figure is saved with the extension .fig This is a format that can only be processed properly by Matlab, but retains all the properties of the figure when it is reloaded.
  • If you want to use the figures with another programme, e.g. to include them in a report written with Word, you must use a file format other than .fig. To do this, you can save as described above, but you must select the desired file format, e.g. jpg or pdf , and adjust the file extension accordingly.

You can also import files that were not created by Matlab (e.g. text, image, Excel files, etc.). The most important commands for this are described today, further possibilities can be found in the help.

Tasks:

T2C1) Create a variable A=[1 2 3; 4 5 6]. Save it with save MatrixA.

  • Check the "Current Folder" window to see if the new file appears there.
  • To make sure that the matrix is really saved, delete it from the workspace with clear A.
  • Load the matrix again with load MatrixA. Check that the matrix A is present in the workspace again.

T2C2) Define an additional variable Matrix B=[0 0 1; 1 0 0] and calculate C=A+B and D=A.*B.

  • Save the entire workspace with save taskT2C2.
  • Delete all variables with clear all from the workspace.
  • Load TaskT2C2 again and check that all variables are back.

T2C3) Often you do not want to save all variables that happen to be in the workspace, but only a selection.

  • Try out the following sequence:
    • save MatrixCD C D
    • clear all
    • load MatrixCD
  • What is now available in the workspace?
  • And what if you once again load MatrixA again?

T2C4) Instead of typing load FILENAME, you can also display the Current Folder in the window on the left and select the desired file by double-clicking on it. Try this out with taskT2C2.mat.

T2C5) Attention! When loading variables, the values of variables with the same name are overwritten. Starting from the current workspace, define a new variable A=1andthen load MatrixA.mat. What happens in the workspace?

T2C6) Copy the following file into your directory and load it into Matlab: grosse_Matrix.mat.

  • How many rows and columns does this matrix have?
  • Look at the matrix with the Array Editor.
  • Pick out the 4th column and the 10th row as vectors.

T2C7) Look at MatrixA.mat in any text editor.

  • What do you see?
  • If you want to save values from Matlab and use them with another programme, it is better to save the file with the option -ascii option. E.G:
    • clear;
    • E=[89 76 0.1 9.7];
    • save -ascii
    • MatrixE.txt
  • Look at the result in the text editor and in Matlab.
  • Try out what happens if you write several variables in a text file.

T2C8) Create a subdirectory in your personal Matlab directory. Try out two ways of writing a file to this subdirectory:

  • First, change to the directory and save there.
  • Then change back to the original directory one level higher and save with save subfolder/filename2 (use a different file name than when you first saved, otherwise the file will be overwritten).
  • Try to load both files from the main directory as well as from the subdirectory.

T2C9) Create a figure with two graphs displayed, e.g. two parabolas as on the first day of the course. Save the figure in the standard format .fig by using the menu item >File >Save as.

  • *) Zoom into the figure and save the figure under a different name.
  • Then close the graphics window and load the two images you have just saved via >File >open in the main menu.
  • Try to reproduce the entire graph again when displaying the section.

T2C10) Try saving the figure you created in the last exercise as a jpg file, closing it and opening it again with Matlab.

  • *) What do you have to do to view it again?
  • *) Can you get back to the entire curve from a section of the curve?
  • *) Try importing both a figure in .fig format and in .jpg format into Word.

T2C11) Since you usually want to view graphics before saving them anyway, the menu bar is a good way to do this. However, in some cases (e.g. if you need many identically formatted images for your bachelor thesis) you may want to save images from a script or a function. The saveas command is available for this purpose. However, so that this command knows which graphic is to be saved, it must be given a name during plotting.

  • Try it out:
    • x=1:1:100; y=sqrt(x);
    • h=plot(x,y);
    • saveas(h,'testbild.fig')
  • Close the image and load testbild.figneu.
  • The practical thing about this type of saving is that Matlab can save different formats directly and recognises the desired file format by the extension of the file name. Among other things .jpg, .eps, .pdf and .bmp can be used. (The complete list of possible formats and their extensions can be found in the help under saveas.)
  • *) Try saving the image as a bmp , for example, and importing it into Word.

T2C12) A frequently used application is the import of text files that have been saved with another programme.

If the file contains only numbers and each line of the file contains the same number of numbers, you can use the normal load command in Matlab.

  • Create a test file with a text programme testfile.txt e.g. with the entries
    • 5 7 9 13.6
    • 0.5 100 1 17
  • Save it as a TEXT file (NOT word!) e.g. as testdatei.txt and load it into Matlab with A=load('testdatei.txt') and load it into Matlab.

*) In more complicated cases, specialised commands are required, the use of which can be found in the help if required, e.g.

  • dlmread (delimited characters read) if the numerical entries are separated by certain characters such as semicolons.
  • textread is used to read files that contain mixed numeric and ASCII data.
  • The Matlab import wizard helps to import all possible file formats.

* T2C13) Especially for users of Excel: Matlab can read excel files with the command variable=xlsread('dateinme.xls')

  • Try this with the file [removals.xls] file.
  • The command xlswrite('filename',variable) is supposed to save a file in xls format (but does not work on my Apple), try it on the Windows computers by creating a large matrix, saving it and opening it in Excel.
  • You can also copy-paste directly back and forth between the array editor in Matlab and Excel, but in Excel you must first select the area into which you want to copy a matrix. Try this out too.

* T2C14) In principle, Matlab can import many formats - but doing this manually is often tedious. That is why there is the "Matlab import wizard" to help with this. If you are interested, have a look at the help section to find out how to use it. For a list of different import functions for various file formats (including sound and films), please search for the keyword "File Formats" in the Help.

D) HOMEWORK

Command reference: Matlab syntax

T2H1) Write a function that returns the four "corners" (top left, top right, bottom left, bottom right) as a vector from an arbitrary matrix.

T2H2) Download the following function, save it in your directory and look at it with the Matlab editor: kompliziert.m

  • How many input and output arguments does this function have?
  • Try to reproduce the sequence of the programme steps in the editor. What does the function do?
  • Test your hypothesis using suitable input parameters. If you delete the semicolon, you can follow the individual steps in the command window. Alternatively, use the debugging function of the editor.
  • Comment the function.
  • *) What happens if the function is not called with two matrices of the same size as specified in the help text? Why?

T2H3) The values of a vector v can be represented graphically with plot(v) as learnt yesterday.

  • Write a function that takes a matrix and a scalar value n as input and plots the nth row of this matrix.
  • Test the function with a few different sized matrices (preferably also with very large ones).
  • What is in the surprise matrix [surprise.mat]?

* T2H4) As already mentioned, functions can also call other functions. Write a function that displays the first, the middle and the last column of a matrix in a new graphics window, using the function from T2H3. A new graph window is opened with the figure command.

* T2H5) Write a function that returns the elements on the diagonal of a square matrix as a vector.

* T2H6) You also learnt about some functions yesterday, e.g. sin and rem. How many input and output arguments do each of these functions have? Have a look in the help.

To the 3rd day of the course

(Changed: 11 Feb 2026)  Kurz-URL:Shortlink: https://uol.de/p36842en
Zum Seitananfang scrollen Scroll to the top of the page

This page contains automatically translated content.