# Introduction to MATLAB

• MATLAB is interpreted, not compiled

• Variables
• no need to declare in advance -- in fact, can't declare
• no need to specify type
• can switch from one type to another
• assign value with '='
• if type name all by itself, with no semicolon, value printed to screen (in fact, this is true for any expression which doesn't end in semicolon)

• Workspace
• save it with save filename
• record all commands typed with diary filename
• stop recording with diary off

• Script files
• place commands into a file mycommands.m (the name must end with .m)
• type name of file, e.g. mycommands, and everything is executed

• Arithmetic
• standard operators + - * /
• exponent operator ^
• use parantheses to specify order of operations
• there are no C-like ++ or +=

• Built-in Functions
• lots and lots and lots of 'em -- see Appendix pages A-7 and A-8 for the basic math functions
• all trig functions take arguments in radians (not degrees)
• pi is pre-defined to mean 3.14159...
• i is pre-defined to mean "square root of negative 1"; square roots of negative numbers yield complex results
• type help foobar to get help on function "foobar"

• Printing values
• Method 1: type the variable or expression without semicolon
• Method 2: use the disp function
• Method 3: use fprintf or sprintf -- very flexible
• print to screen: fprintf(1, 'value of a is 0.00\n', a)
• print to stderr: fprintf(2, 'value of a is 0.00\n', a)
• note that the format string (like all strings) is defined by single-quote (apostrophe) characters ', rather than by double-quote (quotation marks) characters "
• to print to a file,
1. open the file: fid = fopen(filename, 'w')
2. write to it: fprintf(fid, 'string and integer 0\n', str, int)
3. close the file: fclose(fid)

• Expressions -- for scalar quantities (vectors and matrices have their own set of functions)
• equal to: a == b
• not equal to: a ~= b
this is not the same as the != comparison in C
• greater than: a > b
• less than: a < b
• greater than or equal to: a >= b
• less than or equal to: a <= b

• Control Flow
• If
```  if (a == b)       if (a == b)      if (a == b)
do this           do this          do this
end               else             elseif (a > b)
do that          do that
end              else
do the other thing
end
```

• for
```   for (i = 1 : 10)        for (i = 1 : 0.1 : 2)
x = x + i;              x = sin(i)
end                     end
```
• note that the limits are inclusive at both ends, unlike C
• note that if you include the increment, it falls in the middle of the for loop, unlike C

• while
```   while (i < 100)          while (i < 100)
do something             do something
end                        if (result > i)
break
end
end
```
• note that there is no "continue", like in C
• the break command works in for loops, too