Tech-Note 1109: How Do I Vectorize My Code?
and 1's.
The elements of A that are selected have a '1' in the corresponding position of
the subscripting matrix. For example, if A = 1:5, then A(logical([0 0 1 0 1]))
denotes the third and fifth elements of A:
» A = 1:5;
» A(logical([0 0 1 0 1]))
ans =
3 5
This second type of subscripting is very powerful, and we use it frequently in
the following sections. For more information on subscripting, see the
Using
MATLAB
manual.
2. Basic Array Operations: y(i) = fcn(x1(i), x2(i), .
..)
The simplest type of vector operations in MATLAB can be thought of as
bulk
processing
. In this approach, the same operation is performed for each
corresponding element in a data set (which may include more than one
matrix).
Suppose you have some data from an experiment. The data measurements
are the length L, width W, height H, and mass M of an object, and you want to
find the density D of the object. If you had run the experiment once, you would
just have one value for each of the four observables (i.e., L, W, H, and M are
scalars). Here is the calculation you want to run:
D = M/(L*W*H)
Now, suppose that you actually run the experiment 20 times. Now L, W, H, and
M are vectors of length 20, and you want to calculate the corresponding vector
D, which represents the density for each run.
In most programming languages, you would set up a loop, the equivalent of the