![](http://images-20200215.ebookreading.net/23/1/1/9781482247336/9781482247336__a-computational-introduction__9781482247336__bg206.png)
500 A Computational Introduction to Digital Image Processing, Second Edition
Note that MATLAB convention is to use uppercase names for functions in help texts,
even though the function itself is called in lowercase.
A.7 Programming
MATLAB and Octave have a very rich programming language. Only a small set of
functions is actually “built in” to each system, other functions are written in the system’s
own programming language. We consider two distinct programs: script files and functions.
Script Files
A script file is simply a list of commands to be executed. It may be that we will execute
the same sequence of commands many times; in which case, it is more efficient to write a
file containing those commands. If the file is called
script.m
and placed somewhere on the
path, then simply entering
script at the prompt will execute all the commands in it. Of
course you can use any name you like for your script file! However, it is convention to end
MATLAB files with the extension
.m.
Functions
As we have seen, a function is a MATLAB command that takes an input (one or several
variables) and returns one or several values. Let’s look at a simple example: writing a
function that returns the number of positive values of a matrix. This function will take a
matrix as input and return a single number as output. We have seen that
MATLAB/Octave
>> a>0
produces a matrix with 1’s in the positions of positive elements. So the sum of all elements
in this new matrix is the number we require. We can obtain the sum of matrix elements
using the
sum function. If applied to a vector, sum produces the sum of all its elements. If
applied to a matrix, however,
sum produces a vector whose elements are the sums of the
matrix columns:
MATLAB/Octave
>> sum(a)
ans =
4 -2 -12 4
>> sum(a>0)
ans =
3 2 0 3
So we have two options here: we can use sum twice: