Merge branch 'master' of whale.am28.uni-tuebingen.de:scientificComputing

This commit is contained in:
Jan Grewe 2017-10-24 17:26:30 +02:00
commit 04151d237d
8 changed files with 724 additions and 502 deletions

View File

@ -18,21 +18,20 @@ some hints that help to minimize errors.
\section{Types of errors and error messages}
There are a number of different classes of programming errors and it
is good to know the common ones. When we make a programming error
there are some that will lead to corrupted syntax, or invalid
operations and \matlab{} will \codeterm{throw} an error. Throwing an
error ends the execution of a program and there will be an error
messages shown in the command window. With such messages \matlab{}
tries to explain what went wrong and provide a hint on the possible
cause.
is good to know the common ones. Some of your programming errors will
will lead to violations of the syntax or to invalid operations that
will cause \matlab{} to \codeterm{throw} an error. Throwing an error
ends the execution of a program and there will be an error messages
shown in the command window. With such messages \matlab{} tries to
explain what went wrong and to provide a hint on the possible cause.
Bugs that lead to the termination of the execution may be annoying but
are generally easier to find and fix than logical errors that stay
are generally easier to find and to fix than logical errors that stay
hidden and the results of, e.g. an analysis, are seemingly correct.
\begin{important}[Try --- catch]
There are ways to \codeterm{catch} errors during \codeterm{runtime}
(i.e. when the program is executed) and handle them in the program.
There are ways to \codeterm{catch} errors during \codeterm{runtime}
(i.e. when the program is executed) and handle them in the program.
\begin{lstlisting}[label=trycatch, caption={Try catch clause}]
try
@ -50,12 +49,12 @@ obscure logical errors! Take care when using the \codeterm{try-catch
\end{important}
\subsection{\codeterm{Syntax error}}
\subsection{\codeterm{Syntax errors}}\label{syntax_error}
The most common and easiest to fix type of error. A syntax error
violates the rules (spelling and grammar) of the programming
language. For example every opening parenthesis must be matched by a
closing one or every \keyword{for} loop has to be closed by an
\keyword{end}. Usually, the respective error messages are clear and
closing one or every \code{for} loop has to be closed by an
\code{end}. Usually, the respective error messages are clear and
the editor will point out and highlight most \codeterm{syntax error}s.
\begin{lstlisting}[label=syntaxerror, caption={Unbalanced parenthesis error.}]
@ -67,7 +66,7 @@ Did you mean:
>> mean(random_numbers)
\end{lstlisting}
\subsection{\codeterm{Indexing error}}
\subsection{\codeterm{Indexing error}}\label{index_error}
Second on the list of common errors are the indexing errors. Usually
\matlab{} gives rather precise infromation about the cause, once you
know what they mean. Consider the following code.
@ -96,27 +95,80 @@ ans =
65 % wtf ?!?
\end{lstlisting}
The first two indexing attempts in listing \ref{indexerror_listing}
are rather clear. We are trying to access elements with indices that
are invalid. Remember, indices in \matlab{} start with 1. Negative
numbers and zero are not permitted. In the third attemp we index
using a floating point number. This fails because indices have to be
'integer' values. Using a character as an index (fourth attempt)
leads to a different error message that says that the index exceeds
the matrix dimensions. This indicates that we are trying to read data
behind the length of our variable \codevar{my\_array} which has 100
elements.
The first two indexing attempts in listing \ref{indexerror} are rather
clear. We are trying to access elements with indices that are
invalid. Remember, indices in \matlab{} start with 1. Negative numbers
and zero are not permitted. In the third attemp we index using a
floating point number. This fails because indices have to be 'integer'
values. Using a character as an index (fourth attempt) leads to a
different error message that says that the index exceeds the matrix
dimensions. This indicates that we are trying to read data behind the
length of our variable \varcode{my\_array} which has 100 elements.
One could have expected that the character is an invalid index, but
apparently it is valid but simply too large. The fith attempt
finally succeeds. But why? \matlab{} implicitely converts the
\codeterm{char} to a number and uses this number to address the
element in \varcode{my\_array}.
apparently it is valid but simply too large. The fith attempt finally
succeeds. But why? \matlab{} implicitely converts the \codeterm{char}
to a number and uses this number to address the element in
\varcode{my\_array}. The \codeterm{char} has the ASCII code 65 and
thus the 65th element of \varcode{my\_array} is returned.
\subsection{\codeterm{Assignment error}}
This error occurs when we want to write data into a vector.
Related to the Indexing error this error occurs when we want to write
data into a variable, that does not fit into it. Listing
\ref{assignmenterror} shows the simple case for 1-d data but, of
course, it extents to n-dimensional data. The data that is to be
filled into a matrix hat to fit in all dimensions. The command in line
7 works due to the fact, that matlab automatically extends the matrix,
if you assign values to a range outside its bounds.
\begin{lstlisting}[label=assignmenterror, caption={Assignment errors.}]
>> a = zeros(1, 100);
>> b = 0:10;
>> a(1:10) = b;
In an assignment A(:) = B, the number of elements in A and B must be the same.
>> a(100:110) = b;
>> size(a)
ans =
110 1
\end{lstlisting}
\subsection{\codeterm{Dimension mismatch error}}
Similarly, some arithmetic operations are only valid if the variables
fulfill some size constraints. Consider the following commands
(listing\,\ref{dimensionmismatch}). The first one (line 3) fails
because we are trying to do al elementwise add on two vectors that
have different lengths, respectively sizes. The matrix multiplication
in line 6 also fails since for this operations to succeed the inner
matrix dimensions must agree (for more information on the
matrixmultiplication see box\,\ref{matrixmultiplication} in
chapter\,\ref{programming}). The elementwise multiplication issued in
line 10 fails for the same reason as the addition we tried
earlier. Sometimes, however, things apparently work but the result may
be surprising. The last operation in listing\,\ref{dimensionmismatch}
does not throw an error but the result is something else than the
expected elementwise multiplication.
\begin{lstlisting}[label=dimensionmismatch, caption={Some arithmetic operations make size constraints, violating them leads to dimension mismatch errors.}]
>> a = randn(100, 1);
>> b = randn(10, 1);
>> a + b
Matrix dimensions must agree.
>> a * b % The matrix multiplication!
Error using *
Inner matrix dimensions must agree.
>> a .* b
Matrix dimensions must agree.
>> c = a .* b'; % works but the result may not be what you expected!
>> size(c)
ans =
100 10
\end{lstlisting}
\paragraph{Name error:}
\paragraph{Arithmetic error:}
\section{Logical error}
Sometimes a program runs smoothly and terminates without any
@ -132,9 +184,7 @@ there are a few strategies that should help us.
\item Clean code: Structure your code that you can easily read
it. Comment, but only where necessary. Correctly indent your
code. Use descriptive variable and function names.
\item Keep it simple (below).
\item Read error messages, try to understand what \matlab{} wants to
tell.
\item Keep it simple.
\item Use scripts and functions and call them from the command
line. \matlab{} can then provide you with more information. It will
then point to the line where the error happens.
@ -143,17 +193,20 @@ there are a few strategies that should help us.
\end{enumerate}
\subsection{Avoiding errors}
\subsection{Avoiding errors --- Keep it small and simple}
It would be great if we could just sit down write a program, run it
and be done. Most likely this will not happen. Rather, we will make
mistakes and have to bebug the code. There are a few guidelines that
help to reduce the number of errors.
\subsection{The Kiss principle: 'Keep it small and simple' or 'simple and stupid'}
\shortquote{Debugging time increases as a square of the program's
size.}{Chris Wenham}
\shortquote{Everyone knows that debugging is twice as hard as writing
a program in the first place. So if you're as clever as you can be
when you write it, how will you ever debug it?}{Brian Kernighan}
Break down your programming problems into small parts (functions) that
do exactly one thing. This has already been discussed in the context
of writing scripts and functions. In parts this is just a matter of
@ -163,11 +216,6 @@ conflicts (same or similar names for variables) increases. Remembering
the meaning of a certain variable that was defined in the beginning of
the script is just hard.
\shortquote{Everyone knows that debugging is twice as hard as writing
a program in the first place. So if you're as clever as you can be
when you write it, how will you ever debug it?}{Brian Kernighan}
Many tasks within an analysis can be squashed into a single line of
code. This saves some space in the file, reduces the effort of coming
up with variable names and simply looks so much more competent than a
@ -198,125 +246,89 @@ less resources than the other? (iv) How much do you have to invest
into the development of the most elegant solution relative to its
importance in the project? The decision is up to you.
\subsection{Read error messages carefully and call programs from the command line.}
\section{Error messages}
\section{Debugging strategies}
\begin{ibox}[tp]{\label{stacktracebox}Stacktrace or Stack Traceback}
\end{ibox}
If you find yourself in trouble you can apply a few strategies to
solve the problem.
\begin{enumerate}
\item Lean back and take a breath.
\item Read the error messages and identify the position in the code
where the error happens. Unfortunately this is not always the line
or command that really introduced the bug. In some instances the
actual error hides a few lines above.
\item No idea what the error message is trying to say? Google it!
\item Read the program line by line and understand what each line is
doing.
\item Use \code{disp} to print out relevant information on the command
line and compare the output with your expectations. Do this step by
step and start at the beginning.
\item Use the \matlab{} debugger to stop execution of the code at a
specific line and proceed step by step. Be sceptical and test all
steps for correctness.
\item Call for help and explain the program to someone else. When you
do this start at the beginning and walk thorough the code line by
line. Often it is not necessary that the other person is a
programmer or exactly understands what is going on. Often it is the
own refelction on the probelem and the chosen approach that helps
finding the bug. (This is strategy is also known as \codeterm{Rubber
duck debugging}.
\end{enumerate}
Es hilft ungemein, wenn zusammengeh\"orige Skripte und Funktionen im
gleichen Ordner auf der Festplatte zu finden sind. Es bietet sich also
an, f\"ur jede Analyse einen eigenen Ordner anzulegen und in diesem
die zugeh\"origen \codeterm{m-files} abzulegen. Auf eine tiefere
Schachtelung in weitere Unterordner kann in der Regel verzichtet
werden. \matlab{} erzeugt einen ``MATLAB'' Ordner im eigenen
\file{Documents} (Linux) oder \file{Eigene Dokumente} (Windows)
Ordner. Es bietet sich an, diesen Ordner als Wurzelverzeichnis f\"ur
eigene Arbeiten zu verwenden. Nat\"urlich kann auch jeder andere Ort
gew\"ahlt werden. In dem Beispiel in \figref{fileorganizationfig} wird
innerhalb dieses Ordners f\"ur jedes Projekt ein eigener Unterordner
erstellt, in welchem wiederum f\"ur jedes Problem, jede Analyse ein
weiterer Unterodner erstellt wird. In diesen liegen sowohl die
ben\"otigten \codeterm{m-files} also auch die Resultate der Analyse
(Abbildungen, Daten-Dateien). Zu bemerken sind noch zwei weitere
Dinge. Im Projektordner existiert ein Skript (analysis.m), das dazu
gedacht ist, alle Analysen aufzurufen. Des Weiteren gibt es parallel
zu den Projektordnern einen \file{functions}-Ordner in dem Funktionen
liegen, die in mehr als einem Projekt oder einer Analyse gebraucht
werden.
\begin{figure}[tp]
\includegraphics[width=0.75\textwidth]{no_bug}
\titlecaption{\label{fileorganizationfig} M\"ogliche Organisation von
Programmcode im Dateisystem.}{ F\"ur jedes Projekt werden
Unterordner f\"ur die einzelnen Analysen angelegt. Auf Ebene des
Projektes k\"onnte es ein Skript (hier ``analysis.m'') geben,
welches alle Analysen in den Unterordnern anst\"o{\ss}t.}
\subsection{Debugger}
The \matlab{} editor (figure\,\ref{editor_debugger}) supports
interactive debugging. Once you save a m-file in the editor and it
passes the syntax check, i.e. the little box in the upper right corner
of the editor window is green or orange, you can set on or several
\codeterm{break point}s. When the porgram is executed by calling it
from the command line it will be stopped at the line with the
breakpoint. In the editor this is indicated by a green arrow. The
command line will change too to indicate that we are now stopped in
debug mode (listing\,\ref{debuggerlisting}).
\begin{figure}
\centering
\includegraphics[width=0.9\linewidth]{editor_debugger.png}
\caption{Screenshot of the \matlab{} m-file editor. Once a file is
saved and passes the syntax check the green indicator (top-right
corner of the editor window), a breakpoint can be set. Breakpoints
can bes set either using the dropdown menu on top or by clicking
the line number on the left margin. An active breakpoint is
indicated by a red dot.}\label{editor_debugger}
\end{figure}
\Section{Namensgebung von Funktionen und Skripten}
\matlab{} sucht Funktionen und Skripte ausschlie{\ss}lich anhand des
Namens. Dabei spielt die Gro{\ss}- und Kleinschreibung eine Rolle. Die
beiden Dateien \file{test\_funktion.m} und \file{Test\_Funktion.m}
zwei unterschiedliche Funktionen benennen k\"onnen. Diese Art der
Variation des Namens ist nat\"urlich nicht sinnvoll. Sie tr\"agt keine
Information \"uber den Unterschied der beiden Funktionen. Auch sagt
der Name nahezu nichts \"uber den Zweck der Funktion aus.
Die Namensgebung f\"allt mitunter nicht leicht --- manchmal ist es
sogar der schwierigste Aspekt des Programmierens! Ausdrucksstarke
Namen zu finden lohnt sich aber. Ausdrucksstark bedeutet, dass sich
aus dem Namen R\"uckschl\"usse auf den Zweck ziehen lassen sollte.
\begin{important}[Benennung von Funktionen und Skripten]
Die Namen von Funktionen und Skripten sollten m\"oglichst viel \"uber
die Funktionsweise oder den Zweck aussagen (\file{firingrates.m}
statt \file{uebung.m}). Gute Namen f\"ur Funktionen und Skripte sind
die beste Dokumentation.
\end{important}
In Namen verbietet \matlab{} verbietet Leerzeichen, Sonderzeichen und
Umlaute. Namen d\"urfen auch nicht mit Zahlen anfangen. Es mach f\"ur
die Namensgebung selbst keine weiteren Vorgaben. Allerdings folgt die
Benennung der in \matlab{} vordefinierten Funktionen gewissen Mustern:
\begin{itemize}
\item Namen werden immer klein geschrieben.
\item Es werden gerne Abk\"urzungen eingesetzt (z.B. \code{xcorr()}
f\"ur die Kreuzkorrelation oder \code{repmat()} f\"ur ``repeat matrix'')
\item Funktionen, die zwischen Formaten konvertieren sind immer nach
dem Muster ``format2format'' (z.B. \code{num2str()} f\"ur die
Konvertierung ``number to string'', Umwandlung eines numerischen
Wertes in einen Text) benannt.
\end{itemize}
\begin{important}[Benennung von Variablen]
Die Namen von Variablen sollten m\"oglichst viel \"uber ihren Inhalt
aussagen (\varcode{spike\_count} statt \varcode{x}). Gute Namen
f\"ur Variablen sind die beste Dokumentation.
\end{important}
\begin{lstlisting}[label=chaoticcode, caption={Un\"ubersichtliche Implementation des Random-walk.}]
\begin{lstlisting}[label=debuggerlisting, caption={Command line when the program execution was stopped in the debugger.}]
>> simplerandomwalk
6 for run = 1:num_runs
K>>
\end{lstlisting}
\pagebreak[4]
When stopped in the debugger we can view and change the state of the
program at this step and try the next steps etc. Beware, however that
the state of a variable can be altered or even deleted which might
affect the execution of the remaining code.
\begin{lstlisting}[label=cleancode, caption={\"Ubersichtliche Implementation des Random-walk.}]
num_runs = 10;
max_steps = 1000;
positions = zeros(max_steps, num_runs);
The toolbar of the editor offers now a new set of tools for debugging:
\begin{enumerate}
\item \textbf{Continue} --- simply move on until the program terminates or the
execution reaches the next breakpoint.
\item \textbf{Step} --- Execute the next command and stop.
\item \textbf{Step in} --- If the next command is the execution of a
function step into it and stop at the first command.
\item \textbf{Step out} --- If the next command is a function call,
proceed until the called function returns, then stop.
\item \textbf{Run to cursor} --- Execute all statements up to the
current cursor position.
\item \textbf{Quit debugging} --- Immediately stop the debugging
session and stop the further code execution.
\end{enumerate}
for run = 1:num_runs
for step = 2:max_steps
x = randn(1);
if x < 0
positions(step, run) = positions(step-1, run) + 1;
elseif x > 0
positions(step, run) = positions(step-1, run) - 1;
end
end
end
\end{lstlisting}
The debugger offers some more (advanced) features but the
functionality offered by the basic tools is often enough to debug the
code.
% \begin{exercise}{logicalVector.m}{logicalVector.out}
% Erstelle einen Vektor \varcode{x} mit den Werten 0--10.
% \begin{enumerate}
% \item F\"uhre aus: \varcode{y = x < 5}
% \item Gib den Inhalt von \varcode{y} auf dem Bildschirm aus.
% \item Was ist der Datentyp von \varcode{y}?
% \item Gibt alle Elemente aus \varcode{x} zur\"uck, die kleiner als 5 sind.
% \end{enumerate}
% \pagebreak[4]
% \end{exercise}

Binary file not shown.

After

Width:  |  Height:  |  Size: 508 KiB

View File

@ -14,8 +14,7 @@
%%%%% text size %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage[left=20mm,right=20mm,top=25mm,bottom=25mm]{geometry}
\pagestyle{headandfoot} \header{{\bfseries\large \"Ubung
3}}{{\bfseries\large Boolesche Ausdr\"ucke, logisches
Indizieren}}{{\bfseries\large 31. Oktober, 2016}}
3}}{{\bfseries\large Boolean Expressions and logical indexing}}{{\bfseries\large 24. Oktober, 2017}}
\firstpagefooter{Dr. Jan Grewe}{Phone: 29 74588}{Email:
jan.grewe@uni-tuebingen.de} \runningfooter{}{\thepage}{}
@ -31,25 +30,24 @@
\vspace*{-6.5ex}
\begin{center}
\textbf{\Large Einf\"uhrung in die wissenschaftliche Datenverarbeitung}\\[1ex]
\textbf{\Large Introduction to scientific computing}\\[1ex]
{\large Jan Grewe, Jan Benda}\\[-3ex]
Abteilung Neuroethologie \hfill --- \hfill Institut f\"ur Neurobiologie \hfill --- \hfill \includegraphics[width=0.28\textwidth]{UT_WBMW_Black_RGB} \\
\end{center}
Die folgenden Aufgaben dienen der Wiederholung, \"Ubung und
Selbstkontrolle und sollten eigenst\"andig bearbeitet und gel\"ost
werden. Die L\"osung soll in Form eines einzelnen Skriptes (m-files)
im ILIAS hochgeladen werden. Jede Aufgabe sollte in einer eigenen
``Zelle'' gel\"ost sein. Die Zellen \textbf{m\"ussen} unabh\"angig
voneinander ausf\"uhrbar sein. Das Skript sollte nach dem Muster:\newline
``boolesche\_ausdruecke\_\{nachname\}.m'' benannt werden
(z.B. variablen\_datentypen\_mueller.m).
The exercises are meant for self-monitoring, revision of the lecture
topic. You should try to solve them on your own. Your solution should
be submitted as a single script (m-file) in the Ilias system. Each
task should be solved in its own ``cell''. Each cell must be
executable on its own. The file should be named according to the following pattern:
``variables\_datatypes\_\{lastname\}.m'' benannt werden
(e.g. variables\_datentypes\_mueller.m).
\section{Boolesche Ausdr\"ucke}
\section{Boolean expressions}
\begin{questions}
\question Gegeben sind zwei Vektoren \verb+x = [1 5 2 8 9 0 1]+ und
\verb+y = [5 2 2 6 0 0 2]+. F\"uhre aus und erkl\"are.
\question Consider the following vectors \verb+x = [1 5 2 8 9 0 1]+ and
\verb+y = [5 2 2 6 0 0 2]+. Execute the following commands and explain.
\begin{parts}
\part \verb+x > y+
\part \verb+y < x+
@ -59,32 +57,29 @@ voneinander ausf\"uhrbar sein. Das Skript sollte nach dem Muster:\newline
\part \verb+x | y+
\end{parts}
\question Finde heraus, was die Funktionen \verb+bitand+ und \verb+bitor+ machen.
\question Find out what the functions \verb+bitand+ and \verb+bitor+ do.
\begin{parts}
\part F\"uhre aus und erkl\"are: \verb+bitand(10, 8)+
\part F\"uhre aus und erkl\"are: \verb+bitor(10, 8)+
\part Execute and explain: \verb+bitand(10, 8)+
\part Execute and explain: \verb+bitor(10, 8)+
\end{parts}
\item Implementiere folgende Boolesche Ausdr\"ucke. Teste mit
zuf\"alligen ganzzahlingen Werten f\"ur \verb+x+ und \verb+y+.
\item Implemen the following Boolean expressions. Test using randomly selected integer values for \verb+x+ and \verb+y+.
\begin{parts}
\part Das Ergebnis sei wahr, wenn \verb+x+ gr\"o{\ss}er als \verb+y+ und die
Summe aus \verb+x+ und \verb+y+ nicht kleiner als 100 ist.
\part Das Ergebnis sei wahr, wenn \verb+x+ und \verb+y+ ungleich 0
oder \verb+x+ und \verb+y+ gleich sind.
\part The result should be \verb+true+ if \verb+x+ greater than \verb+y+ and the sum of \verb+x+ and \verb+y+ is not less than 100.
\part The result shoudl be \verb+true+ if \verb+x+ and \verb+y+ are not equal zero or \verb+x+ and \verb+y+ are equal.
\end{parts}
\end{questions}
\newpage
\section{Logische Indizierung}
\section{Logical Indexing}
Boolesche Ausdr\"ucke k\"onnen benutzt werden um aus Vektoren und
Matrizen die Elemente herauszusuchen, die einem bestimmeten Kriterium
entsprechen.
Boolean expressions can be used to select elements of vectors or
matrices that match in certain criteria. This process is called
logical indexing.
\begin{questions}
\question Gegeben sind \verb+x = (1:10)+ und
\verb+y = [3 1 5 6 8 2 9 4 7 0]+. Versuche die Ausgaben folgender
Anweisungen zu verstehen. Erkl\"are die Ergebnisse.
\question Given are the vectors \verb+x = (1:10)+ and
\verb+y = [3 1 5 6 8 2 9 4 7 0]+. Try to understand the results of
the following commands. Explain.
\begin{parts}
\part \verb+x < 5+
\part \verb+x( x < 5) )+
@ -93,15 +88,11 @@ entsprechen.
\part \verb+x( (x == 0) & (y == 0) )+
\end{parts}
\question Teste den Zufallsgenerator:
\question Test the random number generator:
\begin{parts}
\part Erzeuge eine 100x100 2-D Matrize mit Zufallswerten zwischen
0 und 100 (\verb+randi+). Ersetze die Werte der Elemente, die in
folgende Klassen fallen: \verb+x < 33+ mit 0,
\verb+x >= 33 und x < 66+ mit 1 und alle \verb+x >= 66+ auf 2.
\part Ermittle die Anzahl Elemente f\"ur jede Klasse mithilfe eines
Booleschen Ausdrucks (\verb+sum+ kann eingesetzt werden um die
Anzahl Treffer zu ermitteln).
\part Create a 100x100 2-D matrix that is filled with random numbers in the range 0 to 100 (\verb+randi+). Replace the elements according to these rules: \verb+x < 33+ to 0,
\verb+x >= 33 and x < 66+ to 1 and all \verb+x >= 66+ to 2.
\part Count the number of elements in each class using Boolean expressions (\verb+sum+ can be used to count the matches).
\end{parts}
\end{questions}

View File

@ -0,0 +1,229 @@
\documentclass[12pt,a4paper,pdftex]{exam}
\usepackage[german]{babel}
\usepackage{natbib}
\usepackage{graphicx}
\usepackage[small]{caption}
\usepackage{sidecap}
\usepackage{pslatex}
\usepackage{amsmath}
\usepackage{amssymb}
\setlength{\marginparwidth}{2cm}
\usepackage[breaklinks=true,bookmarks=true,bookmarksopen=true,pdfpagemode=UseNone,pdfstartview=FitH,colorlinks=true,citecolor=blue]{hyperref}
%%%%% text size %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage[left=20mm,right=20mm,top=25mm,bottom=25mm]{geometry}
\pagestyle{headandfoot}
\header{{\bfseries\large Exercise 3}}{{\bfseries\large Matrices}}{{\bfseries\large 23. Oktober, 2017}}
\firstpagefooter{Dr. Jan Grewe}{Phone: 29 74588}{Email:
jan.grewe@uni-tuebingen.de}
\runningfooter{}{\thepage}{}
\setlength{\baselineskip}{15pt}
\setlength{\parindent}{0.0cm}
\setlength{\parskip}{0.3cm}
\renewcommand{\baselinestretch}{1.15}
\newcommand{\code}[1]{\texttt{#1}}
\renewcommand{\solutiontitle}{\noindent\textbf{Solutions:}\par\noindent}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}
\vspace*{-6.5ex}
\begin{center}
\textbf{\Large Introduction to Scientific Computing}\\[1ex]
{\large Jan Grewe, Jan Benda}\\[-3ex]
Neuroethology \hfill --- \hfill Institute for Neurobiology \hfill --- \hfill \includegraphics[width=0.28\textwidth]{UT_WBMW_Black_RGB} \\
\end{center}
The exercises are meant for self-monitoring, revision of the lecture
topic. You should try to solve them on your own. Your solution should
be submitted as a single script (m-file) in the Ilias system. Each
task should be solved in its own ``cell''. Each cell must be
executable on its own. The file should be named according to the following pattern:
``variables\_datatypes\_\{lastname\}.m'' benannt werden
(e.g. variables\_datentypes\_mueller.m).
\begin{questions}
\question Create the following matrix:
\[ A = \left( \begin{array}{ccc} 7 & 3 & 5 \\ 1 & 8 & 3 \\ 8 & 6 &
4 \end{array} \right) \]
\begin{parts}
\part Use the function \code{size} to check for its size.
\begin{solution}
\code{x = [7 3 5; 1 8 3; 8 6 4];\\disp(size(x))}
\end{solution}
\part Use the help to figure out how to get only the size along a certain axis. Print the sizes of each dimension.
\begin{solution}
\code{disp(size(x, 1))}\\\code{disp(size(x, 2))}
\end{solution}
\part Retrieve the element at the position 3rd line, 2nd column.
\begin{solution}
\code{x(3,2)}
\end{solution}
\part Print all elements of the 1st, 2nd and 3rd line.
\begin{solution}
\code{disp(x([1 2 3],:));}
\end{solution}
\part Print all elements of the 1st, 2nd, and 3rd column.
\begin{solution}
\code{disp(x(:, 1))\\ disp(x(:, 2))\\ disp(x(:, 3))}
\end{solution}
\part Increment all elements of the 2nd line and the 3rd column about 1.
\begin{solution}
\code{x(2,3) = x(2,3) + 1;}
\end{solution}
\part Subtract five from all elements of the 1st line.
\begin{solution}
\code{x(1,:) = x(1,:) - 5;}
\end{solution}
\part Multiply all elements of the 3rd column with 2.
\begin{solution}
\code{x(:,3) = x(:,3) .* 2;}
\end{solution}
\end{parts}
\question Create a $5 \times 5$ matrix \code{M} that contains random numbers (use the function
\verb+randn()+. Use the help to find out what it does).
\begin{parts}
\part Print the element at the position 2nd line and 3rd column.
\begin{solution}
\code{M = randn(5, 5);}
\code{disp(M(2,3))}
\end{solution}
\part Print all elements of the 1st, 3rd and last line.
\begin{solution}
\code{disp(M(1,:)) \\ disp(M(3,:))\\ disp(M(size(M,1), :))}
\end{solution}
\part Print the elements of the 2nd and 4th column.
\begin{solution}
\code{disp(M(:,2))\\ disp(M(:,4))}
\end{solution}
\part Select with a single command all elements of every 2nd column and store them in a new variable.
\begin{solution}
\code{y = M(:, [2:2:size(M,2)])}
\end{solution}
\part Calculate the averages of lines 1, 3, and 5 (use the function mean, see help).
\begin{solution}
\code{mean(M([1 3 5],:), 2)}
\end{solution}
\part Calculate the sum of all elements in the 2nd and 4th column
(function \code{sum}, see help).
\begin{solution}
\code{sum(M(:, [2 4]), 1)}
\end{solution}
\part Calculate the total sum of all elements in \code{M}
\begin{solution}
\code{sum(M(:))}
\end{solution}
\part Exchange all elements of the 2nd with those of the 4th line.
\begin{solution}
\code{M(2,:) = M(4,:)}
\end{solution}
\part Execute the following command: \code{M(1:2,1) = [1, 2,
3]}. What could have been intended by the command and what does the error message tell?
\begin{solution}
\code{M(1:2,1) = [1, 2,3];\\ Subscripted assignment dimension
mismatch.} \\ Der einzuf\"ugende Vektor hat 3 Elemente, die
Auswahl von M in die geschrieben werden soll hat nur die
Gr\"o{\ss}e 2;
\end{solution}
\end{parts}
\question Indexing in matrices can use the
\textit{subscript} indices or the \textit{linear} indices (you may want to check the help for the \verb+sub2ind+ and \verb+ind2sub+).
\begin{parts}
\part Create a 2-D matric filled with random numbers and the dimensionality
\verb+[10,10]+.
\begin{solution}
\code{x = randn(10, 10)}
\end{solution}
\part How many elements are stored in it?
\begin{solution}
\code{disp(numel(x))}
\end{solution}
\part Employ linar indexing to select 50 random values.
\begin{solution}
\code{x(randi(100, 50, 1)])}
\end{solution}
\part Is there an advantage to use the linear indexing?
\begin{solution}
Die Matrize ist 2-dimensional. Wenn mit dem subscript index
zugegriffen werden soll, dann muss auf die Dimensionen
einzeln geachtet werden. Mit dem linearen Indexieren kann einfach
einen Vektor mit n Indices benutzt werden. Wenn es auch noch eine
eindeutige (ohne doppelte) Auswahl sein soll, dann muss bei
2-D viel komplexer kontrollieren.
\end{solution}
\part Calculate the total sum of all elements with a single command.
\begin{solution}
\code{sum(x(:))} or \code{sum(sum(x))}
\end{solution}
\end{parts}
\question Create the three variables \verb+x = [1 5 9]+ and
\verb+y = [7 1 5]+ and \verb+M = [3 1 6; 5 2 7]+. Which of the following commands will pass? Which command will not? If not, why? Test your predictions.
\begin{parts}
\part \code{x + y}
\begin{solution}
works!
\end{solution}
\part \code{x * M}
\begin{solution}
Matrixmultiplication will not work! Inner dimensions must agree!
\end{solution}
\part \code{x + y'}
\begin{solution}
Fail! Dimensionalities do not match.
\end{solution}
\part \code{M - [x y]}
\begin{solution}
Fail! \code{[x y] is a line vector of length 6, M is a martix.}
\end{solution}
\part \code{[x; y]}
\begin{solution}
Works! Size: 2 3
\end{solution}
\part \code{M - [x; y]}
\begin{solution}
Works!
\end{solution}
\end{parts}
\question Create a 3-D matrix from two 2-D matrices. Use the function cat (check the help to learn its usage).
\begin{parts}
\part Select all elements of the first ``page'' (index 1, 3. dimension).
\begin{solution}
\code{x = randn(5,5); \\y = randn(5, 5);\\ z = cat(3, x, y);\\disp(z(:,:,1))}
\end{solution}
\end{parts}
\question Create a $5 \times 5 \times 5$ matrix of random numbers that have been drawn from a uniform distribution. Values should be in the range 0 and 100.
\begin{parts}
\part Calculate the average of each ``page'' (function \verb+mean()+, see help).
\begin{solution}
\code{x = round(rand(5,5,5) .* 100);\\ Disp(mean(mean(x(:,:,1))))\\ disp(mean(mean(x(:,:,2)))) \\ disp(mean(mean(x(:,:,3))))}
\end{solution}
\end{parts}
\end{questions}
\end{document}

View File

@ -1,4 +1,4 @@
\documentclass[12pt,a4paper,pdftex]{exam}
\documentclass[12pt,a4paper,pdftex, answers]{exam}
\usepackage[german]{babel}
\usepackage{natbib}

View File

@ -0,0 +1,200 @@
\documentclass[12pt,a4paper,pdftex, answers]{exam}
\usepackage[german]{babel}
\usepackage{natbib}
\usepackage{graphicx}
\usepackage[small]{caption}
\usepackage{sidecap}
\usepackage{pslatex}
\usepackage{amsmath}
\usepackage{amssymb}
\setlength{\marginparwidth}{2cm}
\usepackage[breaklinks=true,bookmarks=true,bookmarksopen=true,pdfpagemode=UseNone,pdfstartview=FitH,colorlinks=true,citecolor=blue]{hyperref}
%%%%% text size %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage[left=20mm,right=20mm,top=25mm,bottom=25mm]{geometry}
\pagestyle{headandfoot}
\header{{\bfseries\large Exercise 2}}{{\bfseries\large Vectors}}{{\bfseries\large 18. Oktober, 2017}}
\firstpagefooter{Dr. Jan Grewe}{Phone: 29 74588}{Email:
jan.grewe@uni-tuebingen.de}
\runningfooter{}{\thepage}{}
\setlength{\baselineskip}{15pt}
\setlength{\parindent}{0.0cm}
\setlength{\parskip}{0.3cm}
\renewcommand{\baselinestretch}{1.15}
\newcommand{\code}[1]{\texttt{#1}}
\renewcommand{\solutiontitle}{\noindent\textbf{Solutions:}\par\noindent}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}
\vspace*{-6.5ex}
\begin{center}
\textbf{\Large Introduction to Scientific Computing}\\[1ex]
{\large Jan Grewe, Jan Benda}\\[-3ex]
Neuroethology \hfill --- \hfill Institute for Neurobiology \hfill --- \hfill \includegraphics[width=0.28\textwidth]{UT_WBMW_Black_RGB} \\
\end{center}
The exercises are meant for self-monitoring and revision of the lecture
topic. You should try to solve them on your own. Your solution should
be submitted as a single script (m-file) in the Ilias system. Each
task should be solved in its own ``cell''. Each cell must be
executable on its own. The file should be named according to the following pattern:
``variables\_datatypes\_\{lastname\}.m'' benannt werden
(e.g. variables\_datentypes\_mueller.m).
\begin{questions}
\question Create vector with the following contents:
\begin{parts}
\part Integer numbers ranging from 1 to 10.
\begin{solution}
\code{a = 1:10;}
\end{solution}
\part Integer numbers in the range 0 to 20 in steps of 2.
\begin{solution}
\code{a = 0:2:20;}
\end{solution}
\part \textbf{Descending} values ranging from 100 to 0.
\begin{solution}
\code{a = 100:-1:0;}
\end{solution}
\part In 10 steps from 0 to 1.
\begin{solution}
\code{a = 0:0.1:1;}
\end{solution}
\part In 11 steps from 0 to 1.
\begin{solution}
\code{a = 0:1/11:1;}
\end{solution}
\part In 50 steps from 0 to $2\pi$ ($\pi$ is known in Matlab as the constant
\code{pi}).
\begin{solution}
\code{a = 0:2*pi/50:2*pi;}
\end{solution}
\end{parts}
\question Calculations with vectors:
\begin{parts}
\part Create a vector \code{x = [3 2 6 8];}
\part What is the size of this vector? Use the functions \code{size} and \code{length}. What is the difference between them?
\begin{solution}
\code{x = [3 2 6 8];
\\ disp(length(x));\\ 4\\ disp(size(x))\\ 1 4}
\end{solution}
\part What changes in \code{size} and \code{length} when you transpose the vector.
\begin{solution}
The length does not change, the size is inverted.
\end{solution}
\part Add 5 to each element of \verb+x+.
\begin{solution}
\code{disp(x + 5)}
\end{solution}
\part Multiply each element of \code{x} with 2;
\begin{solution}
\code{disp(x * 2)}
\end{solution}
\part Create a second vector (\verb+y = [4 1 3 5];+).
Make sure that \code{x} is in its original form.
\part Add both vectors \code{x + y}.
\begin{solution}
\code{y = [4 1 3 5]; \\disp(x + y)\\7 3 9 13}
\end{solution}
\part Subtract \code{y} from \code{x}.
\begin{solution}
\code{disp(x - y)\\-1 1 3 3}
\end{solution}
\part Multiply both vectors \code{x * y}.
\begin{solution}
\code{disp(x * y)\\Error using *. Inner matrix dimension must agree.}
\end{solution}
\part Explain the error message
\begin{solution}
* operator is the matrix multiplication. The inner dimensions must agree.\linebreak
\code{disp(size(x))\\1 4 \\disp(size(y)) \\ 1 4}\\
(m,n)*(n,o) w\"are ok.
\end{solution}
\part What needs to be done to make \code{mtimes} and
\code{*} working?
\begin{solution}
y needs to be transposed: \code{x * y'}
\end{solution}
\part Multiply element-wise (\code{x .* y}) and assign the result to a new variable.
\begin{solution}
\code{z = x .* y;}
\end{solution}
\end{parts}
\question Creating vectors using helper functions:
\begin{parts}
\part Create a vector of the length 100 using the function
\code{ones} (see help). What is its purpose?
\begin{solution}
\code{ones(100,1)} creates a vector of the given size and fills it with 1.
\end{solution}
\part Create a vector of the length 100 using the function
\code{zeros} (see help). What is its purpose?
\begin{solution}
\code{zeros(100,1)} creates a vector of the given size and fills it with 0.
\end{solution}
\part Create a vector with 100 elements. All elements should have the value
4.5.
\begin{solution}
\code{ones(100, 1) * 4.5}
\end{solution}
\part Create a 100 element vector filled with random numbers (\code{rand},
see help).
\begin{solution}
\code{x = rand(100, 1)}
\end{solution}
\part Use the function \code{linspace} to create a 100 element vector with values between 0 and 1.
\begin{solution}
\code{x = linspace(0, 1, 100)}
\end{solution}
\end{parts}
\question Indexing in vectors:
\begin{parts}
\part Create a 100 element length vector with values ranging from 0 to 99.
\begin{solution}
\code{x = linspace(0, 99, 100);}
\end{solution}
\part Print the first, last, fifth, 24th and the second-to-last value.
\begin{solution}
\code{disp(x(1))\\ disp(x(end))\\ disp(x(5))\\ disp(x(24))\\ disp(x(end-1))}
\end{solution}
\part Print the first 10 values.
\begin{solution}
\code{x(1:10)}
\end{solution}
\part Print the last 10 values.
\begin{solution}
\code{disp(x(end-9:end))}
\end{solution}
\part Try to print the value at the zeroth position.
\begin{solution}
\code{x(0)\\ Subscript indices must either be real positive integers or logicals.}
\end{solution}
\part Try to access the value at the 110th position.
\begin{solution}
\code{x(110)\\ Index exceeds matrix dimensions.}
\end{solution}
\part Access the values at the positions 3, 15, and 42 with a single command.
\begin{solution}
\code{disp(x([3 15 42]))}
\end{solution}
\part Access 10 randomly selected values (used \verb+randi+ to create random indices).
\begin{solution}
\code{x(randi(100,10,1))}
\end{solution}
\end{parts}
\question Store some text in a valriable. The text should consist of at least two words (e.g. \code{x = 'some
text'}). Use indexing to print out the words individually.
\begin{solution}
\code{x = 'some text'; \\ disp(x(1:4))\\disp(x(6:end))}
\end{solution}
\end{questions}
\end{document}

View File

@ -1,4 +1,4 @@
\documentclass[12pt,a4paper,pdftex]{exam}
\documentclass[12pt,a4paper,pdftex, answers]{exam}
\usepackage[german]{babel}
\usepackage{natbib}
@ -13,10 +13,11 @@
%%%%% text size %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage[left=20mm,right=20mm,top=25mm,bottom=25mm]{geometry}
\pagestyle{headandfoot} \header{{\bfseries\large \"Ubung
2}}{{\bfseries\large Vektoren und Matrizen}}{{\bfseries\large 12. Oktober, 2015}}
\pagestyle{headandfoot}
\header{{\bfseries\large Exercise 2}}{{\bfseries\large Vectors}}{{\bfseries\large 18. Oktober, 2017}}
\firstpagefooter{Dr. Jan Grewe}{Phone: 29 74588}{Email:
jan.grewe@uni-tuebingen.de} \runningfooter{}{\thepage}{}
jan.grewe@uni-tuebingen.de}
\runningfooter{}{\thepage}{}
\setlength{\baselineskip}{15pt}
\setlength{\parindent}{0.0cm}
@ -24,387 +25,176 @@
\renewcommand{\baselinestretch}{1.15}
\newcommand{\code}[1]{\texttt{#1}}
\renewcommand{\solutiontitle}{\noindent\textbf{L\"osung:}\par\noindent}
\renewcommand{\solutiontitle}{\noindent\textbf{Solutions:}\par\noindent}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}
\vspace*{-6.5ex}
\begin{center}
\textbf{\Large Einf\"uhrung in die wissenschaftliche Datenverarbeitung}\\[1ex]
\textbf{\Large Introduction to Scientific Computing}\\[1ex]
{\large Jan Grewe, Jan Benda}\\[-3ex]
Abteilung Neuroethologie \hfill --- \hfill Institut f\"ur Neurobiologie \hfill --- \hfill \includegraphics[width=0.28\textwidth]{UT_WBMW_Black_RGB} \\
Neuroethology \hfill --- \hfill Institute for Neurobiology \hfill --- \hfill \includegraphics[width=0.28\textwidth]{UT_WBMW_Black_RGB} \\
\end{center}
Die folgenden Aufgaben dienen der Wiederholung, \"Ubung und
Selbstkontrolle und sollten eigenst\"andig bearbeitet und gel\"ost
werden. Die L\"osung soll in Form eines einzelnen Skriptes (m-files)
im ILIAS hochgeladen werden. Jede Aufgabe sollte in einer eigenen
``Zelle'' gel\"ost sein. Die Zellen \textbf{m\"ussen} unabh\"angig
voneinander ausf\"uhrbar sein. Das Skript sollte nach dem Muster:
\linebreak ``vektoren\_matrizen\_\{nachname\}.m'' benannt werden
(z.B. vektoren\_matrizen\_mueller.m).
The exercises are meant for self-monitoring and revision of the lecture
topic. You should try to solve them on your own. Your solution should
be submitted as a single script (m-file) in the Ilias system. Each
task should be solved in its own ``cell''. Each cell must be
executable on its own. The file should be named according to the following pattern:
``variables\_datatypes\_\{lastname\}.m'' benannt werden
(e.g. variables\_datentypes\_mueller.m).
\begin{questions}
\section*{Vektoren}
\question Erzeuge Vektoren mit folgendem Inhalt:
\question Create vector with the following contents:
\begin{parts}
\part Von 1 bis 10 in ganzzahligen Schritten.
\part Integer numbers ranging from 1 to 10.
\begin{solution}
\code{a = 1:10;}
\end{solution}
\part Von 0 bis 20 in 2er Schritten.
\part Integer numbers in the range 0 to 20 in steps of 2.
\begin{solution}
\code{a = 0:2:20;}
\end{solution}
\part Mit \textbf{absteigendem} Inhalt von 100 bis 0.
\part \textbf{Descending} values ranging from 100 to 0.
\begin{solution}
\code{a = 100:-1:0;}
\end{solution}
\part In 10 Schritten von 0 bis 1.
\part In 10 steps from 0 to 1.
\begin{solution}
\code{a = 0:0.1:1;}
\end{solution}
\part In 11 Schritten von 0 bis 1.
\part In 11 steps from 0 to 1.
\begin{solution}
\code{a = 0:1/11:1;}
\end{solution}
\part In 50 Schritten von 0 bis $2\pi$ ($\pi$ ist als Konstante
\code{pi} in Matlab definiert).
\part In 50 steps from 0 to $2\pi$ ($\pi$ is known in Matlab as the constant
\code{pi}).
\begin{solution}
\code{a = 0:2*pi/50:2*pi;}
\end{solution}
\end{parts}
\question Rechnen mit Vektoren:
\question Calculations with vectors:
\begin{parts}
\part Definiere einen Vektor \code{x = [3 2 6 8];}
\part Wie gro{\ss} ist der Vektor? Benutze die Funktionen
\code{size} und \code{length}. Was ist der Unterschied zwischen
den beiden Funktionen?
\part Create a vector \code{x = [3 2 6 8];}
\part What is the size of this vector? Use the functions \code{size} and \code{length}. What is the difference between them?
\begin{solution}
\code{x = [3 2 6 8]; \\ disp(length(x));\\ 4\\ disp(size(x))\\ 1 4}
\code{x = [3 2 6 8];
\\ disp(length(x));\\ 4\\ disp(size(x))\\ 1 4}
\end{solution}
\part Wie \"andern sich \code{size} und \code{length} des
Vektors wenn er transponiert wird?
\part What changes in \code{size} and \code{length} when you transpose the vector.
\begin{solution}
L\"ange \"andert sich nicht. R\"uckgabewert von size ist invertiert.
The length does not change, the size is inverted.
\end{solution}
\part Addiere 5 zu jedem Element von \verb+x+.
\part Add 5 to each element of \verb+x+.
\begin{solution}
\code{disp(x + 5)}
\end{solution}
\part Multipliziere jedes Element von \code{x} mit 2;
\part Multiply each element of \code{x} with 2;
\begin{solution}
\code{disp(x * 2)}
\end{solution}
\part Definiere einen zweiten Vektor (\verb+y = [4 1 3 5];+).
Stelle sicher, dass \code{x} wieder in seiner urspr\"unglichen
Form ist.
\part Addiere beide Vektoren \code{x + y}.
\part Create a second vector (\verb+y = [4 1 3 5];+).
Make sure that \code{x} is in its original form.
\part Add both vectors \code{x + y}.
\begin{solution}
\code{y = [4 1 3 5]; \\disp(x + y)\\7 3 9 13}
\end{solution}
\part Subtrahiere beide Vektoren \code{x - y}.
\part Subtract \code{y} from \code{x}.
\begin{solution}
\code{disp(x - y)\\-1 1 3 3}
\end{solution}
\part Multipliziere beide Vektoren \code{x * y}.
\part Multiply both vectors \code{x * y}.
\begin{solution}
\code{disp(x * y)\\Error using *. Inner matrix dimension must agree.}
\end{solution}
\part Erkl\"are die Fehlermeldung.
\part Explain the error message
\begin{solution}
* ist der Operator f\"ur die Matrixmultiplikation. Bei dieser
muessen die inneren Dimensionen \"uebereinstimmen.\linebreak
* operator is the matrix multiplication. The inner dimensions must agree.\linebreak
\code{disp(size(x))\\1 4 \\disp(size(y)) \\ 1 4}\\
(m,n)*(n,o) w\"are ok.
\end{solution}
\part Was m\"usste man machen, damit \code{mtimes} bzw. der
\code{*} Operator funktionieren?
\part What needs to be done to make \code{mtimes} and
\code{*} working?
\begin{solution}
y m\"usste transponiert werden: \code{x * y'}
y needs to be transposed: \code{x * y'}
\end{solution}
\part Multipliziere die Vektoren elementweise (\code{x .* y})
und weise das Ergebnis eine neuen Variablen zu.
\part Multiply element-wise (\code{x .* y}) and assign the result to a new variable.
\begin{solution}
\code{z = x .* y;}
\end{solution}
\end{parts}
\question Erzeugen von Vektoren mit Helferfunktionen:
\question Creating vectors using helper functions:
\begin{parts}
\part Erstelle einen 100 Elemente langen Vektor mit der Funktion
\code{ones} (siehe Hilfe). Was macht sie?
\part Create a vector of the length 100 using the function
\code{ones} (see help). What is its purpose?
\begin{solution}
\code{ones(100,1)} erzeugt einen Vektor bei dem alle Elemente mit 1 gef\"ullt sind.
\code{ones(100,1)} creates a vector of the given size and fills it with 1.
\end{solution}
\part Erstelle einen 100 Elemente langen Vektor mit der Funktion
\code{zeros}. Was macht diese?
\part Create a vector of the length 100 using the function
\code{zeros} (see help). What is its purpose?
\begin{solution}
\code{zeros(100,1)} erzeugt einen Vektor bei dem alle Elemente mit 0 gef\"ullt sind.
\code{zeros(100,1)} creates a vector of the given size and fills it with 0.
\end{solution}
\part Erstelle einen 100 Elemente langen Vektor in dem jedes
Element den Wert 4.5 hat.
\part Create a vector with 100 elements. All elements should have the value
4.5.
\begin{solution}
\code{ones(100,1) * 4.5}
\code{ones(100, 1) * 4.5}
\end{solution}
\part Erzeuge einen Vektor mit 100 Zufallszahlen (\code{rand},
siehe Hilfe).
\part Create a 100 element vector filled with random numbers (\code{rand},
see help).
\begin{solution}
\code{x = rand(100,1)}
\code{x = rand(100, 1)}
\end{solution}
\part Erzeuge einen Vektor mit 100 Werten zwischen 0 und 1
mithilfe der Funktion \code{linspace}.
\part Use the function \code{linspace} to create a 100 element vector with values between 0 and 1.
\begin{solution}
\code{x = linspace(0,1,100)}
\code{x = linspace(0, 1, 100)}
\end{solution}
\end{parts}
\question Indizieren in Vektoren:
\question Indexing in vectors:
\begin{parts}
\part Erzeuge einen Vektor mit 100 Elementen (0 - 100).
\part Create a 100 element length vector with values ranging from 0 to 99.
\begin{solution}
\code{x = linspace(0,100,100);}
\code{x = linspace(0, 99, 100);}
\end{solution}
\part Gib jeweils den ersten, den letzten, den 5., 24. und den
vorletzten Wert aus.
\part Print the first, last, fifth, 24th and the second-to-last value.
\begin{solution}
\code{disp(x(1))\\ disp(x(end))\\ disp(x(5))\\ disp(x(24))\\ disp(x(end-1))}
\end{solution}
\part Gib die ersten 10 Werte aus.
\part Print the first 10 values.
\begin{solution}
\code{x(1:10)}
\end{solution}
\part Gib die letzten 10 Werte aus.
\part Print the last 10 values.
\begin{solution}
\code{disp(x(end-9:end))}
\end{solution}
\part Versuche den Wert an der Stelle 0 auszugeben.
\part Try to print the value at the zeroth position.
\begin{solution}
\code{x(0)\\ Subscript indices must either be real positive integers or logicals.}
\end{solution}
\part Versuche den Wert an der Stelle 110 auszugeben.
\part Try to access the value at the 110th position.
\begin{solution}
\code{x(110)\\ Index exceeds matrix dimensions.}
\end{solution}
\part Gib die Werte an den Stellen 3, 15, und 42 zusammen als
Vektor aus.
\part Access the values at the positions 3, 15, and 42 with a single command.
\begin{solution}
\code{disp(x([3 15 42]))}
\end{solution}
\part Gib 10 zuf\"allig ausgew\"ahlte Werte aus (benutze
\verb+randi+ um die Indizes zu erstellen).
\part Access 10 randomly selected values (used \verb+randi+ to create random indices).
\begin{solution}
\code{x(randi(100,10,1))}
\end{solution}
\end{parts}
\question Erzeuge eine Variable und speichere etwas Text in ihr,
so dass mindestens 2 Worte vorhanden sind. (z.B. \code{x = 'some
text'}). Benutze die Indizierung um die W\"orter einzeln
auszugeben.
\question Store some text in a valriable. The text should consist of at least two words (e.g. \code{x = 'some
text'}). Use indexing to print out the words individually.
\begin{solution}
\code{x = 'some text'; \\ disp(x(1:4))\\disp(x(6:end))}
\end{solution}
\newpage
\section*{Matrizen}
\question Erstelle folgende Matrix
\[ A = \left( \begin{array}{ccc} 7 & 3 & 5 \\ 1 & 8 & 3 \\ 8 & 6 &
4 \end{array} \right) \]
\begin{parts}
\part Benutze die Funktion \code{size} um die Gr\"o{\ss}e vpm \code{A} anzeeigen zu lassen.
\begin{solution}
\code{x = [7 3 5; 1 8 3; 8 6 4];\\disp(size(x))}
\end{solution}
\part Finde heraus, wie man \code{size} aufruft um nur die L\"ange entlang einer einzelnen Dimension auszugeben. Gib einzeln die L\"angen beider Dimensionen aus.
\begin{solution}
\code{disp(size(x, 1))}\\\code{disp(size(x, 2))}
\end{solution}
\part Gib das Element in der 3. Zeile und 2. Spalte aus.
\begin{solution}
\code{x(3,2)}
\end{solution}
\part Gib jeweils alle Elemente der 1., 2. und 3. Zeile aus.
\begin{solution}
\code{disp(x([1 2 3],:));}
\end{solution}
\part Gib jeweils alle Elemente der 1., 2., und 3. Spalte aus.
\begin{solution}
\code{disp(x(:, 1))\\ disp(x(:, 2))\\ disp(x(:, 3))}
\end{solution}
\part Erh\"ohe das Element in der 2. Zeile und 3. Spalte um Eins.
\begin{solution}
\code{x(2,3) = x(2,3) + 1;}
\end{solution}
\part Ziehe von allen Elementen der 1. Zeile 5 ab.
\begin{solution}
\code{x(1,:) = x(1,:) - 5;}
\end{solution}
\part Multipliziere alle Elementen der 3. Spalte mit 2.
\begin{solution}
\code{x(:,3) = x(:,3) * 2;}
\end{solution}
\end{parts}
\question Erstelle eine $5 \times 5$ Matrix \code{M} die
Zufallszahlen enth\"alt (nutze die MATLAB Funktion
\verb+randn()+. Benutze die Hilfe: Was macht die Funktion?).
\begin{parts}
\part Gib das Element in der 2. Zeile und 3. Spalte aus.
\begin{solution}
\code{M = randn(5, 5);}
\code{disp(M(2,3))}
\end{solution}
\part Gib jeweils alle Elemente der 1., 3. und letzten Zeile aus.
\begin{solution}
\code{disp(M(1,:)) \\ disp(M(3,:))\\ disp(M(size(M,1), :))}
\end{solution}
\part Gib jeweils alle Elemente der 2. und 4. Spalte aus.
\begin{solution}
\code{disp(M(:,2))\\ disp(M(:,4))}
\end{solution}
\part Greife mit einem einzigen Kommando auf die Elemente jeder
zweiten Spalte zu und speichere die Daten in einer neuen Variable.
\begin{solution}
\code{y = M(:, [2:2:size(M,2)])}
\end{solution}
\part Berechne jeweils den Mittelwert der 1., 3. und 5. Zeile
(Funktion \code{mean}, siehe Hilfe).
\begin{solution}
\code{mean(M([1 3 5],:), 2)}
\end{solution}
\part Berechne die Summe aller Werte der 2. und 4. Spalte
(Funktion \code{sum}, siehe Hilfe).
\begin{solution}
\code{sum(M(:, [2 4]), 1)}
\end{solution}
\part Berechne die Summe aller Elemente der Matrize.
\begin{solution}
\code{sum(M(:))}
\end{solution}
\part Ersetze die Elemente der 2. Zeile mit denen der 4.
\begin{solution}
\code{M(2,:) = M(4,:)}
\end{solution}
\part F\"uhre folgendes Kommando aus: \code{M(1:2,1) = [1, 2,
3]}. Was k\"onnte die Absicht dieses Codes gewesen sein? Was
bedeutet die Fehlermeldung?
\begin{solution}
\code{M(1:2,1) = [1, 2,3];\\ Subscripted assignment dimension
mismatch.} \\ Der einzuf\"ugende Vektor hat 3 Elemente, die
Auswahl von M in die geschrieben werden soll hat nur die
Gr\"o{\ss}e 2;
\end{solution}
\end{parts}
\question Matrizen k\"onnen neben der ``normalen''
\textit{subscript} Indizierung auch \textit{linear} indiziert werden
(siehe Hilfe \"uber Indexing oder Funktionen \verb+sub2ind+ oder
\verb+ind2sub+).
\begin{parts}
\part Erstelle eine 2-D Matrix mit Zufallszahlen mit der Dimensionalit\"at
\verb+[10,10]+.
\begin{solution}
\code{x = randn(10, 10)}
\end{solution}
\part Wie viele Werte enth\"alt sie?
\begin{solution}
\code{disp(numel(x))}
\end{solution}
\part Benutze das lineare Indizieren um 50 zuf\"allige Werte
auszuw\"ahlen.
\begin{solution}
\code{x(randi(100, 50, 1)])}
\end{solution}
\part Wo liegt der Vorteil gegen\"uber der \textit{subscript}
Indizierung?
\begin{solution}
Die Matrize ist 2-dimensional. Wenn mit dem subscript index
zugegriffen werden soll, dann muss auf die Dimensionen
einzeln geachtet werden. Mit dem linearen Indexieren kann einfach
einen Vektor mit n Indices benutzt werden. Wenn es auch noch eine
eindeutige (ohne doppelte) Auswahl sein soll, dann muss bei
2-D viel komplexer kontrollieren.
\end{solution}
\part Berechne die Summe aller Werte mit einem Funktionsaufruf..
\begin{solution}
\code{sum(x(:))} oder \code{sum(sum(x))}
\end{solution}
\end{parts}
\question Erstelle folgende Variablen \verb+x = [1 5 9]+ and
\verb+y = [7 1 5]+ und \verb+M = [3 1 6; 5 2 7]+. Welche der
folgenden Operationen funktionieren? Wenn nicht, warum funktionieren
sie nicht? Teste Deine Vorhersagen.
\begin{parts}
\part \code{x + y}
\begin{solution}
Funktioniert!
\end{solution}
\part \code{x * M}
\begin{solution}
Matrixmultiplikation Funktioniert nicht! Inner dimensions must agree!
\end{solution}
\part \code{x + y'}
\begin{solution}
Funktioniert nicht! Die Dimensionalit\"aten passen nicht.
\end{solution}
\part \code{M - [x y]}
\begin{solution}
Funktioniert nicht! \code{[x y] ist ein Zeilenvektor der L\"ange
6, M ist eine Martix.}
\end{solution}
\part \code{[x; y]}
\begin{solution}
Funktioniert! Gr\"o{\ss}e: 2 3
\end{solution}
\part \code{M - [x; y]}
\begin{solution}
Funktioniert!
\end{solution}
\end{parts}
\question Erstelle eine 3-D Matrix aus drei 2-D Matrizen. Benutze
die \verb+cat()+ Funktion f\"ur diesen Zweck (schaue in der Hilfe
nach, wie sie benutzt wird).
\begin{parts}
\part Gib alle Elemente des ersten ``Blattes'' aus (Index 1 der 3. Dimension).
\begin{solution}
\code{x = randn(5,5); \\y = randn(5, 5);\\ z = cat(3, x, y);\\disp(z(:,:,1))}
\end{solution}
\end{parts}
\question Erzeuge eine $5 \times 5 \times 5$ Matrix die mit
ganzzahligen, gleichverteilten Zufallszahlen zwischen 0 und 100
gef\"ullt ist.
\begin{parts}
\part Berechne den Mittelwert aller Bl\"atter dieser Matrix
(benutze \verb+mean()+, siehe Hilfe).
\begin{solution}
\code{x = round(rand(5,5,5) .* 100);\\ Disp(mean(mean(x(:,:,1))))\\ disp(mean(mean(x(:,:,2)))) \\ disp(mean(mean(x(:,:,3))))}
\end{solution}
\end{parts}
\end{questions}
\end{questions}
\end{document}

View File

@ -1,6 +1,6 @@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Programming in \matlab}
\chapter{Programming in \matlab}\label{programming}
\section{Variables and data types}