⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 matlab小技巧.txt

📁 电子书:matlab基础基础及其应用。这是学习matlab的很好的书
💻 TXT
字号:
1109	How Do I Vectorize My Code?
Revision 1.0

This technical note provides an introduction to vectorization
techniques.  In order to understand some of the tricks available, an
introduction to MATLAB indexing is provided.  Then several
vectorization techniques are discussed, in order of simplest to most
complicated.

There are two aspects to this presentation.  Knowledge of all the
techniques available is only half of the battle.  The other half is
knowing when to use them -- recognizing situations where this approach
or that one is likely to yield a better (quicker, cleaner) algorithm.
Each section provides an example, which proceeds from a description of
the problem to a final solution.  We hope that illustrating the
process by example achieves both of these goals.

1.  MATLAB Subscripting

A powerful feature of MATLAB is the ability to select subsets of an
array or matrix.  There are two types of subscripting available in
MATLAB.

In indexed subscripting, the values of the subscript are the indices
of the matrix where the matrix's values are desired.  Thus, if A =
1:5, then A([3,5]) denotes the third and fifth elements of matrix A:

     >>A = 1:5;
     >>A([3,5])

     ans =

          3     5

The second type of subscripting is logical subscripting.  With this
type of subscripting, the subscript is a matrix the same size as A
containing only 0's 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([0 0 1 0 1]) denotes the third and fifth elements of A:

     >>A = 1:5;
     >>A([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 MATLAB User's Guide, pp. 2-26 to 2-32.

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 following MATLAB code:

     >>for i = 1:20
        D(i) = M(i)/(L(i)*W(i)*H(i));
      end

The beauty of MATLAB is that it allows you to ignore the fact that you
actually ran 20 experiments.  You can perform the calculation
element-by-element over each vector, with (almost) the same syntax as
the first equation, above:

     >>D = M./(L.*W.*H);

The only difference is the use of the .* and ./ operators.  These
differentiate element-by-element operators, called array operators,
from the (quite different) linear algebra operators, called matrix
operators.  For example, * denotes matrix multiplication, ^ denotes
matrix exponentiation, etc.  (See Strang, Linear Algebra with
Applications, for an introduction to linear algebra operators.)  In
this context you should use the array operators, although the matrix
operators will become useful later on.

3.  Boolean Array Operations: y = bool(x1, x2, ...)

A logical extension of the bulk processing idea is to vectorize
comparisons and decision making.  MATLAB comparison operators, like
the array operators above, accept vector inputs and produce vector
outputs.

Suppose that, after running the above experiment, you find that
negative numbers have been measured for the mass.  As these values are
clearly erroneous, you decide that those runs for the experiment are
invalid.

You can find out which runs are valid using the >= operator on the vector M:

     >>M = [-.2 1.0 1.5 3 -1 4.2 3.14];
     >>M>=0

     ans =

          0     1     1     1     0     1     1

Now you can exploit the indexing power of MATLAB to remove the
erroneous values:

     >>D = (M>=0)
     
       D =
 
          0     1     1     1     0     1     1


This selects the subset of D for which the corresponding elements of M
are non-negative.

Suppose further that, if all values for masses are negative, you want
to display a warning message and exit the routine.  You need a way to
condense the vector of Boolean values into a single value.  There are
two vectorized Boolean operators, any and all, which perform Boolean
AND and OR functions over a vector.  Thus you can perform the
following test:

     if all(M<0)
        disp('Warning: all values of mass are negative.');
        return;
     end

You can also compare two vectors of the same size using the Boolean
operators, resulting in expressions such as:

     >>(M>=0) & (L>H)

The result is a vector of the same size as the inputs.

Here are two notes on the use of the Boolean functions.  First, since
MATLAB uses IEEE arithmetic, there are special values to denote
overflow, underflow, and undefined operations: Inf, -Inf, and NaN,
respectively.  Inf and -Inf can be tested for normally (i.e., Inf ==
Inf returns true), but, by the IEEE standard, NaN is never equal to
anything (even other NaN's).  Therefore, there are special Boolean
operators, isnan and isinf, to help test for these values.

Second, if you try to compare two matrices of different sizes, an
error results.  You need to check sizes explicitly if the operands
might not be the same size.

4.  Constructing Matrices from Vectors:  y(:,i) = f(x(:))

Creating some simple matrices, like constant matrices, is easy in
MATLAB.  The following code creates a matrix of all 10s:

     >>A = ones(5,5)*10

It turns out that the multiplication here is not necessary; we can get
around it using an indexing trick.  We'll see this in a moment.

Another common application involves selecting specified elements of a
vector to create a new matrix.  This is often a simple application of
the indexing power of MATLAB.  For example, to create a matrix
corresponding to elements [2, 3; 5, 6; 8, 9; 11, 12; ...] of a vector
x:

     >>x = 1:51;
     >>x = reshape(x, 3, length(x)/3);
     >>A = x(2:3,:)';

We are using indexing to exploit the symmetry of the desired matrix.
There are several tools available to exploit different types of
symmetry.

There is a famous trick for duplicating a vector of size M by 1, n
times, to create a matrix of size M by N .  In this method, known as
Tony's Trick, the first column of the vector is indexed (or
referenced, or selected) n times:

     >>v = (1:5)';
     >>M = v(:,ones(3,1))

     M =
          1     1     1
          2     2     2
          3     3     3
          4     4     4
          5     5     5

Now we realize how our first matrix, size 5 by 5 constant matrix of
all 10s, can be created without matrix multiplication:

     >>A = 10;
     >>A = A(ones(5))

      A =
           10    10    10    10    10
           10    10    10    10    10
           10    10    10    10    10
           10    10    10    10    10
           10    10    10    10    10

The same trick can be applied to row vectors, by switching the
subscripts.  It can also duplicate specific rows or columns of a
matrix, provided that you are not selecting the first row or column,
or that the resulting matrix is not the same size as the original
matrix.  If these conditions both hold, then there is an ambiguity.
The subscripting vector, which is all ones, could represent logical
subscripting where all columns or rows are chosen once, or it could
represent indexed subscripting where just the first column or row is
chosen several times.  In the case of ambiguity, MATLAB chooses to
view the intent as logical subscripting.  For example,

     >>A = magic(3)

     A =

        8     1     6
        3     5     7
        4     9     2

     >>A(:,ones(1,3))

     ans =

        8     8     8
        3     3     3
        4     4     4

     >>A(:,ones(1,2))

     ans =

        8     8
        3     3
        4     4
     >>prm=[3 2 1]'
       prm =

           3
           2
           1
     >>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -