Day 03
Data types and case distinctions
Status: 01.10.2014
Attention! Outdated html version! Please use pdf version!
24.08.2016: The .pdf file of the script has been updated. Please use the new version.
Command reference: Matlab syntax
pdf version of the script: [Tag03.pdf]
Word version of the script: [Tag03.docx]
Downloads: all files at once: [downloads_Tag03.zip]
T3C3) [phValues.mat]
T3H2) and T3H3) [katzen.mat]
HTML version:
A) CASE DISTINCTIONS
Up to now, all programmes in the course have followed a simple recipe: individual steps were executed in sequence (linear algorithm). Now we go one step further and introduce alternatives as to how the further programme sequence should be continued at a certain point. (E.g. "If you want to bake blueberry muffins, add blueberries to the muffin batter, alternatively you can also use raspberries.") These branches in the programme flow are called case distinctions.
Case distinctions are often used to perform different operations for different number ranges of a variable. The comparison operators are used to separate the number ranges from each other
- < less
- > greater
- == Test for equality
- <= less than or equal to
- >= greater than or equal to
- ~= unequal
The general syntax for a case distinction is
if condition
command1
else
command2
end
For example, you might want to handle positive numbers differently than negative and zero:
a=19.7 % or any other number
if a>0 % for positive numbers
b=2*a % set b=2*a
else % for negative numbers and 0
b=-2a % make b positive
end
The indentation is carried out automatically by the Matlab editor. It is not absolutely necessary for the execution of the programme, but makes it much easier to read.
The else part of the case differentiation can also be omitted if you only want something to happen if a condition is true and nothing else needs to be done. E.G.
a=-19.7 % or any other number
% a should always be a positive number
if a<0 % for negative numbers
a=-a % make a positive
end
If more than two conditions are distinguished, you need the syntax
if (condition1)
commands1
elseif(condition2)
commands2
else
commands3
end
(there can be any number of elseif parts).
Conditions can also be combined:
condition1 && condition2 % "And" link, both must apply
condition1 || condition2 % "Or" link, one of both must apply
e.g.
if a>0 && b<0
b=1;
c=a;
elseif a<0 && b>0
a=1;
c=b;
else
c=a*b
end
Tasks:
T3A1) Write a function that receives a number as an input parameter. If this number is negative, it is displayed on the screen, otherwise nothing happens.
T3A2) Write a function that expects a matrix as an input parameter. If this matrix is square, the function returns the number 1, otherwise the number 0.
T3A3) Write a function that receives a number as an input parameter.
- If this is an even number, the function returns half of the number.
- If the input parameter is a 0, a 1 is returned
- otherwise the number itself is returned.
T3A4) Write a function that takes two numbers as input parameters and returns the number of positive input parameters.
B) DATA TYPES: NUMBERS
You have already familiarised yourself with the most important data types in Matlab: scalar values, vectors and matrices consisting of numbers.
- Variables that containnumbers (numeric) are symbolised by four boxes in the Matlab editor
- Numbers are normally defined in Matlab as floating point numbers with double precision (double).
- However, there are also integers (int),
- Which data type you choose depends on the type of data you want to represent.
Floating point numbers(double):
- Floating point numbers can have many digits after the decimal point, e.g. the number PI.
- If you look at pi you will only see four decimal places. However, Matlab actually calculates with many more digits.
- Nevertheless, you must be aware that computers can only calculate with finite precision (defined in Matlab by the constant eps), i.e. the decimal places are cut off at a certain point.
- There is also an upper limit to the number range that can be processed (constant realmax). Above this number, there is only one number for Matlab that can be reliably calculated: inf (infinity).
Integers (int):
- Integers also have a limited representation range.
- Depending on how large the numbers are that you want to represent with an integer variable, there are different types in Matlab that require different amounts of memory: int8, int16, int32 andint64. In each case, the number indicates how many bits of memory are used. For example, with a variable of type int8 2⁸=256 numbers can be represented. As both positive and negative numbers and zero are contained in the range of int8, the displayable range extends from -128 to 127.
- If you are sure that you only want to use positive numbers, you can also use uint8, uint16,uint32 and uint64 ("unsigned integer") can also be used. For uint8 the number range is from 0 to 255.
To convert the type of a variable, use the name of the desired data type. e.g. uint16(a) turns the variable a of any data type into an integer represented by 16 bits.
Tasks:
T3B1) You can use the format command to change how many decimal places are shown in a floating point number.
- Try out how pi and how 100*pi are displayed after you have entered one of the following commands:
-
- format long
- format long e
- format short e
- format shortformat short g
- For which applications is which format best suited?
T3B2) Computers can only display and process a limited (albeit quite large) range of numbers.
- Look at the largest and smallest positive numbers that your computer can reliably calculate with Matlab: realmax, eps
- What happens if you exceed or fall below this range? Try, for example realmax*10, eps/2, realmax+1, 10-eps
T3B3) Two special constants in Matlab usually don't make you happy when you get them as the result of a calculation: inf and nan.
- Look in the help to see what they mean. What is the difference between them?
- Try to generate the two constants using arithmetic operations.
- Create two matrices in which once at a position nan in one place and inf in one place and inf in the other, while all other matrix elements are normal numbers.
- Try to calculate with both matrices. What happens?
T3B4) There are cases for which fractional values do not make sense, but onlyintegers, e.g. when it comes to the number of animals. In particular, this is also the case if you want to index an element of a vector.
- Imagine you have a vector v that contains 100 data points from a series of measurements and you want to know how large your measurement result was after 1/3 of the time. Try out whether this works:
v=0.1:0.1:10;
L=length(v);
ind=L/3;
m=v(ind)
- How does the answer from Matlab look in comparison if you want to look at the measuring point after 1/2 of the time?
- To get rid of the error message, you can explicitly make the index an integer variable:
v=0.1:0.1:10;
L=length(v);
ind=int16(L/3);
m=v(ind)
- An alternative to this is to continue working with the standard data type double, but to round the corresponding number:
v=0.1:0.1:10;
L=length(v);
ind_a=round(L/3);
m_a=v(ind_a)
- However, it is easy to forget such rounding, especially if the numbers are used for further calculations. It is therefore safer to use integers if fractional numbers make no sense. Try it out:
ind=int16(L/3);
m=v(ind);
ind2=ind/2;
m2=v(ind2)
- versus
ind_a=round(L/3);
m=v(ind_a);
ind2_a=ind_a/2;
m2_a=v(ind2_a)
- What data type does ind2? Which ind2_a? What are its values?
C) TRUTH VALUES
Truth values(logical) are another important data type.
- These can only have two values: "true", symbolised by 1and "false", symbolised by 0.
- In the Matlab workspace, variables of type logical are symbolised by a tick.
- Probably the most important application of truth values is the case differentiation already introduced above. The condition in the case distinction generates a truth value on which the further processing of the programme depends.
Logical variables are defined
- by the command logicalcommand, which turns any input into a truth value, e.g. a=logical(0)
- or by the comparison operators already used above <, >, ==, <=, >=, ~= which each return a truth value
- or by other test functions that also return truth values. The tests to determine whether a variable has a specific data type are particularly important:
-
- a=isscalar(x) % True for a scalar value
- a=isvector(x) % True for a vector
- a=isfloat(x) % True for floating point numbers (vectors, matrices, scalars)
- a=isnumeric(x) % True for all numbers (vectors, matrices, scalars)
- a=ischar(x) % True for strings
- a=islogical(x) % True for truth values
- a=isa(x,'type') % True if x has the data type 'type'
You can "calculate" with truth values by using logical operations, e.g. to combine them in the conditions in if statements:
- c= a&&b % logical and,
- % a and b must be true, so that c is true
- c= a||b % logical or,
- % at least one of a and b must be true for c to be true.
- c= ~a % negation.
- % c is true if a is false.
- c= xor(a,b)% Exclusive or,
- % c is true if exactly one of a and b is true.
Tasks:
T3C1) Try out:
- a=logical(0)
- What value and what type does a have in the workspace?
- Also define b=logical(1)
- What happens with c=logical(2)?
T3C2) Try out different comparison operators:
- define two variables with scalar numerical values
- compare them with each of the comparison operators<, >, ==, <=, >=, ~=
- (Syntax tip: w=(a>b) returns the same result as w=a>b, but is easier to read).
- What is the difference between = and == ?
- Apply the comparison operators to two matrices of the same size. What type is the output? What does the calculation rule look like?
T3C3) It can be very helpful to apply comparison operators to vectors or matrices in order to find those measuring points in data for which certain conditions are fulfilled. Load the following series of measurements of the pH value of aquarium water: [phWerte.mat].
- How many of the measurement points are measurement errors (at least if your fish have survived the series of measurements and are normal freshwater fish that normally swim around pH 7)?
- How often were too high and how often too low values recorded?
T3C4) Sometimes you want to test two whole matrices or vectors for equality and not their individual elements. For this, there is the command isequal(M,N), which returns a single truth value.
T3C5) Write a function that returns the type of input for any given input parameter.
D) TEXT
Most programmes need to interact with the user in some way. The most modern option for this is graphical user interfaces (GUIs), which can be designed relatively easily in Matlab. However, we will not be dealing with these in this course. (But if you don't feel that you have enough work to do, you are welcome to familiarise yourself with the use of GUIs with the help of a tutorial). In this section, we will restrict ourselves to the "conventional" form of screen output as text and figures and user input via the keyboard in the command window.
If you want to process texts with Matlab, these are displayed as character strings (array of char).
- Variables of type char are symbolised by abc in the workspace window.
- The syntax for generating a character string and assigning it to a variable is
-
- text='Texts are enclosed in inverted commas'
- You can work with such character strings in the same way as with vectors to index individual characters or character strings or to append character strings one after the other.
- Spaces count in the same way as all other characters.
- To create a longer formatted text, you can also generate a type of matrix in which each line contains a character string. However, it should be noted that each line must be the same length. Therefore, shorter lines must be padded with spaces to avoid error messages. (This is sometimes a bit cumbersome. Next week we will get to know a perhaps somewhat more elegant and frequently used way of dealing with texts).
Tasks:
T3D1) Try it out:
text='Texts are enclosed in inverted commas'
text(1)
part1=text(1:6)
part2=text(17:25)
syntax=[part2 ' ' part1 ' ' part2]
(to make the last expression easier to read, here again with _ for each space:
syntax=[teil2_'_'_teil1_'_'_teil2])
T3D2) We already know that calculation results are displayed in the command window by default if they are not suppressed by a ; at the end of the line.
However, it can be useful to provide the user with other information via text output. This is done using the disp function, which is passed a character string.
- Simply because it is part of a programming course, create a script hello_world.m which contains the following as the only line
disp('hello world')
- Because this is a little boring, add hello_world so that it also tells you the current date in a friendly way. To do this, use the function date.
T3D3) You are now very familiar with a special type of text output: the error messages written in red. You can also generate these yourself using the error command, e.g. with
error('that's not how it works!')
However, the error function does more than just produce a red text output; it also cancels the execution of a programme.
- Try this out by inserting the error command at various points in a longer script or function (e.g. complicated.m from yesterday). If you do not use semicolons in the file or use the debugging mode in the editor, you can see which steps are executed in each case.
T3D4) If you want to warn the user that something is probably going wrong, but do not want to abort the entire programme, you can use the warning command. Try this out too.
T3D5) You can also mix text output with the output of variable values. The command for this is sprintf. This is a function that is passed a character string to be output as the first argument. The key terms %g (for variables of type double, int or logical) or %s (for string) are placed at the positions of the variable values. The variable names are passed as further arguments in the order in which they appear in the text.
- Try it out:
a=0.2;
t='Text';
sprintf('now we can display numbers such as %g and also %s.',a,t)
- Extend one of your spaghetti scripts or functions from yesterday so that the length is output with the unit.
- *) For people with too much time or a penchant for beautiful screen output: with sprintf you can specify the formatting very precisely (e.g. number of decimal places) - you can find out how to do this in the help. There are also notes on the corresponding command fprintfcommand, which can be used to write formatted data to files.
T3D6) Character strings are also used to label images.
- Plot for x1=-10:0.1:10 plot the vector y1=x1.^2.
- Use the commands title, xlabel and ylabelcommands to label your graphic. These commands are each given a character string as an input argument.
- Provide your illustration with the command legend('blablabla') with a legend (possibly with more descriptive text).
- Try plotting several curves in one figure. To do this, create the following for a second x-vector x2=-5:0.1:5 the y-values y2=2*x2.^2. (Reminder: To plot both curves in a figure, you must explicitly specify the x- and y-values in each case, i.e. in our case plot(x1,y1,x2,y2) or hold on in our case).
- Label both curves in the legend. legend receives as many comma-separated strings as the number of vectors shown in the graphic.
T3D7) Often you not only want to tell the user something, but also receive user input. You have already learnt about a special case of this, the pause command. If the value of an input is also to be queried, the command input is used.
a=input('input') assigns a number or a variable value to the variable a. Try it out:
a=input('Value for a: ')
-> enter at query 7
b=input('Value for b: ')
-> enter at query a
c=input('Value for c: ')
-> enter at query xyz
If text is to be read in, the command requires the option 's' as the second input value:
c=input('Value for c: ','s')
-> enter at query xyz
d=input('Value for d: ','s')
-> enter at query 7
e=input('Value for e: ','s')
-> enter at query b
T3D8) To compare character strings, there is the command strcmp(t1,t2) (string comparison), which returnsa logical 1if the character strings t1 and t2 are the same. Alternatively, you can also use the isequal command already introduced above.
- Try ==, isequal and strcmp for the same and different character strings.
T3D9) You can convert strings into numbers and vice versa. The commands for this are num2str (number to string) and str2num. Try it out:
a=1.1
a_char=num2str(a)
a_new=str2num(a_char)
b='xyz';
b_num=str2num(b)
- What types do the variables have in each case?
T3D10) This conversion is particularly useful for automatically generating character strings, e.g. for the systematic naming of files. Write a programme that
- requests two inputs from the user:
-
- a character string and
- a number
- Use the entered number in combination with the fixed character string 'my_file' to generate the file name. For example, if the user enters 5 the file should be named 'my_file5.mat'.
- Save the character string entered by the user in a file with this name.
- Attention, the normal syntax does not work here
-
- save filename variablename
- (This would be expected if the generated file name was stored in the variable filename variable). For this you need the more complicated (and unfortunately very unintuitive) syntax
-
- save(filename, 'variable name')
- (Please don't ask me why there are inverted commas around the variable name!)
T3D11) Attention! Matlab does not prevent you from calculating with strings! Try it out:
a='1'
a2=2*a
a2_ok=2*str2num(a)
b='xyz'
b+1
T3D12) To display programme texts in the command window, there is the command type. Try it out in your working directory:
- type spaghettiskript
- Conveniently type applies not only to your own programmes, but also to those contained in Matlab, so that you can view them without a long search and learn something from them. For example, try type imagesc (no, you don't have to understand the programme code yet).
- However, Matlab does not let you look at some core functions, e.g. type sin
E) HOMEWORK
Command reference: Matlab syntax
*T3H1) Try out which data types can be converted into which.
- Create one variable of each of the different data types you know and convert the type into the other data types.
- What happens, for example, if you turn characters into numbers and vice versa?
- What happens to signs and decimal places when you convert them to other types?
T3H2) The characteristics of the cats in an animal shelter are stored in the following file: [katzen.mat].
- In the vector age vector contains the age of each cat in years,
- In the vector female a trueif the cat is a female, for males a false.
- The characteristics of the animals are arranged in the same order.
- How do you find out how many cats are younger than 2 years old?
- How do you find out the number of females under two years old?
T3H3) In the characteristics of the cats in the shelter [katzen.mat] there is also a colour matrix. This consists of truth values and is structured as follows:
Rows: 23 cats
Column 1: Cat has black fur
Column 2: Cat has red fur
Column 3: Cat has white fur
Column 4: Cat has mackerel fur
- How many cats have tabby coats?
- How many cats have pure mackerel fur, without other colours?
- How many tricoloured lucky cats (black-white-red) are there?
- How many solid-coloured cats are there (if tabby cats are not considered solid-coloured)?
* T3H4) (To be used later ) Write a program that allows visitors to the shelter to find out through a dialogue whether their dream cat exists in the shelter in terms of age, sex and coat colour.
**) The last task can be extended as required. You can decide for yourself how many details you want to include in your programme.
*T3H5) For people with too much time or an increased interest in programming concepts:
Matlab provides a switch statement for queries of many different cases. Look up how to use this in the help (you can also find a short version in the command reference), and write a function "arbeitsamt", which receives a name(string) as input and assigns this name to the responsible clerk and displays their name on the screen. Responsibility for initial letters:
A-D: Ms Schmidt
E-H: Mr Klein
I-L: Ms Gross
M-P: Ms Mueller
Q-T: Mr Maier
U-Z: Mr Dimpfelmoser
*T3H6) For further information, here is a script from another course in which, for example, nested queries are also introduced: