Geoscience Reference
In-Depth Information
B = 2
if A < B
disp('A is less than B')
elseif A >= B
disp('A is not less than B')
end
h e for loops and if-then constructs are extensively used in the following
chapters of the topic. For other aspects of programming, please refer to the
MATLAB documentation (MathWorks 2014a and c).
2.8 Scripts and Functions
MATLAB is a powerful programming language. All i les containing
MATLAB code use .m as an extension and are therefore called M-i les .
h ese i les contain ASCII text and can be edited using a standard text editor.
However, the built-in Editor color-highlights various syntax elements such
as comments in green, keywords such as if , for and end in blue, and character
strings in pink. h is syntax highlighting facilitates MATLAB coding.
MATLAB uses two types of M-i les: scripts and functions. Whereas scripts
are a series of commands that operate on data in the workspace, functions
are true algorithms with input and output variables. h e advantages and
disadvantages of both types of M-i le will now be illustrated by an example.
We i rst start the Editor by typing
edit
h is opens a new window named untitled . Next, we generate a simple
MATLAB script by typing a series of commands to calculate the average of
the elements of a data array x .
[m,n] = size(x);
if m == 1
m = n;
end
sum(x)/m
h e i rst line of the if-then construct yields the dimensions of the variable x
using the command size . In our example x should be either a column vector,
i.e., an array with a single column and dimensions (m,1) , or a row vector, i.e.
an array with a single row and dimensions (1,n) . h e if statement evaluates
a logical expression and executes a group of commands if this expression
is true. h e end keyword terminates the last group of commands. In the
example the if-then construct picks either m or n depending on whether m==1
is false or true. Here, the double equal sign '==' makes element by element
Search WWH ::




Custom Search