Exercise 1 (by Mikael Eriksson, TA HT2015)

If you are completely new at programming and Matlab, and want study materials beyond that in the course, you can google ”Matlab tutorial”. The following PDF looks good: http://se.mathworks.com/help/pdf_doc/matlab/getstart.pdf?s_tid=int_tut

Focus on sections for: expressions, functions, indexing, flow control, loops, and skip sections on mathematical concepts.



Example: Stack as cell array: push, pop, top



Model and diagram for the ”function machine”: input, output, dependencies, effects



Compare ”pre- and post conditions”



Explain difference between returning a value and updating a variable



In Matlab all function arguments are ”by value”, so no way to update external variables unless using pointers or using ”global”, but we won't be talking about pointers in Matlab, so we will pretend that solution is not available. So we have to return values.



Difference between mathematical array and cell array.



How to add and remove elements from cell array.



Do exercises 2 and 3, as ”preparation for lab 1”

Debug with break points



Tips for lab 1:

Tokenizer function: expression string → cell array of tokens (what are the classes of tokens?)

The transform function: array of tokens → array of tokens

The calculate function: array of tokens → number



Deep idea: the above three helps to separate between specifics of input/ouput formats, and the data structure which is good for doing algorithm logic! Doing the transform directly on the string is alot more fuzz and makes it harder to debug!



if there is no

do … until <a or b or c>

how to rewrite as

while ??

Could negate predicate

Or could use ”while true” together with break statement



code examples (I'm afraid tabs don't get exported correctly from Open Office to html, so sorry about the lack of indentation :(. If any one knows how to fix, please let me know). You can use the ”smart indentation” feature button in Matlab to fix indentation in one click though ^^.



pop.m



function [ out ] = pop( stack )

% stack should be a cell array

%remove top element from stack


stack(end) = [];

out = stack;

end





mymultiply.m



function [ out] = mymultiply( a, b )

%


for r = 1:size(a, 1)

for c = 1:size(b, 2)

out(r, c) = a(r, :) * b(:, c)

end

end


end





collatz.m



function [ list ] = collatz( n )

%


list = {};

while n ~= 1

list{end + 1} = n;

if mod(n, 2) == 1

n = 3*n + 1;

else

n = n/2;

end

% One way to make ``do... until''

if n == 1

break % leave the loop

end

end


end