马铃薯®is optimized for operations involving matrices and vectors. The process of revising loop-based, scalar-oriented code to use MATLAB matrix and vector operations is calledvectorization。Vectorizing your code is worthwhile for several reasons:
出现: Vectorized mathematical code appears more like the mathematical expressions found in textbooks, making the code easier to understand.
易于错误:没有循环,矢量化代码通常较短。更少的代码行意味着介绍编程错误的机会较少。
性能: Vectorized code often runs much faster than the corresponding code containing loops.
This code computes the sine of 1,001 values ranging from 0 to 10:
我= 0;对于t = 0:.01:10 i = i + 1;y(i)= sin(t);结束
This is a vectorized version of the same code:
t = 0:.01:10;y = sin(t);
第二代码样本通常比第一个更快地执行,并且更有效地使用MATLAB。通过创建包含所示代码的脚本来测试系统上的执行速度,然后使用tic
andTOC.
函数来衡量其执行时间。
此代码计算每个第五个元素时的向量的累积和:
x = 1:10000; ylength = (length(x) - mod(length(x),5))/5; y(1:ylength) = 0; for n= 5:5:length(x) y(n/5) = sum(x(1:n)); end
Using vectorization, you can write a much more concise MATLAB process. This code shows one way to accomplish the task:
x = 1:10000; xsums = cumsum(x); y = xsums(5:5:length(x));
Array operators perform the same operation for all elements in the data set. These types of operations are useful for repetitive calculations. For example, suppose you collect the volume (V
) of various cones by recording their diameter (D
) and height (H
). If you collect the information for just one cone, you can calculate the volume for that single cone:
V = 1/12*pi*(D^2)*H;
Now, collect information on 10,000 cones. The vectorsD
andH
each contain 10,000 elements, and you want to calculate 10,000 volumes. In most programming languages, you need to set up a loop similar to this MATLAB code:
对于n = 1:10000 V(n)= 1/12 * pi *(d(n)^ 2)* h(n));结束
With MATLAB, you can perform the calculation for each element of a vector with similar syntax as the scalar case:
% Vectorized Calculationv = 1/12 * pi *(d。^ 2)。* h;
Note
放置一段时间(。
)在运营商之前*
,/
, and^
, transforms them into array operators.
Array operators also enable you to combine matrices of different dimensions. This automatic expansion of size-1 dimensions is useful for vectorizing grid creation, matrix and vector operations, and more.
假设矩阵A
代表测试分数,其中的行表示不同的类别。您希望计算每个类的平均分数和各个分数之间的差异。使用循环,操作看起来像:
A = [97 89 84; 95 82 92; 64 80 99;76 77 67;。。。88 59 74; 78 66 87; 55 93 85]; mA = mean(A); B = zeros(size(A));对于n = 1:size(A,2) B(:,n) = A(:,n) - mA(n);结束
A more direct way to do this is witha - 平均(a)
, which avoids the need of a loop and is significantly faster.
deva = a - 意思是(a)
Deva = 18 11 0 16 4 8 -15 2 15 -3 -1 -17 9 -19 -10 -1 -12 3 -24 15 1
Even thoughA
是一个7×3矩阵和mean(A)
是一个1-×3矢量,MATLAB隐式扩展矢量,因为它与矩阵具有与矩阵相同的尺寸,并且操作执行为正常元素 - WISE减去操作。
操作数的大小要求是,对于每个维度,阵列必须具有相同的大小或其中一个。如果满足此要求,则阵列之一具有大小1的尺寸将扩展为相同的大小作为其他阵列中的相应维度。有关更多信息,请参阅兼容数组大小,用于基本操作。
如果您正在使用多维数据,则隐式扩展非常有用的另一个区域。假设您想要评估函数,F
, of two variables,x
andy
。
F(x,y) = x*exp(-x2- y2)
To evaluate this function at every combination of points in thex
andy
向量,您需要定义一个网格的值。为this task you should avoid using loops to iterate through the point combinations. Instead, if one of the vectors is a column and the other is a row, then MATLAB automatically constructs the grid when the vectors are used with an array operator, such asx+y
orx-y
。在这个例子中,x
is a 21-by-1 vector andy
is a 1-by-16 vector, so the operation produces a 21-by-16 matrix by expanding the second dimension ofx
and the first dimension ofy
。
x = (-2:0.2:2)';%21-by-1y = -1.5:0.2:1.5;%1-by-16F = x.*exp(-x.^2-y.^2);%21-by-16
阵列的批量处理的逻辑扩展是矢量化比较和决策。Matlab比较运算符接受向量输入和返回向量输出。
为example, suppose while collecting data from 10,000 cones, you record several negative values for the diameter. You can determine which values in a vector are valid with the>=
操作员:
D = [-0.2 1.0 1.5 3.0 -1.0 4.2 3.14]; D >= 0
ans = 0 1 1 1 0 1 1
vgood.
, for which the corresponding elements ofD
是非不良的:vgood.= V(D >= 0);
MATLAB允许您使用函数执行整个向量的逻辑且或或或或上的元素all
andany
, respectively. You can throw a warning if all values ofD
低于零:
如果所有(d <0)警告('All values of diameter are negative.')返回结束
马铃薯can also compare two vectors with compatible sizes, allowing you to impose further restrictions. This code finds all the values where V is nonnegative andD
is greater thanH
:
V((V >= 0) & (D > H))
为了帮助比较,MATLAB包含特殊值,以表示溢出,下溢和未定义的运算符,例如Inf
and南
。Logical operatorsisinf
andisnan
exist to help perform logical tests for these special values. For example, it is often useful to exclude南
计算中的值:
x = [2 -1 0 3 nan 2 nan 11 4 inf];xvalid = x(〜isnan(x))
xvalid = 2 -1 0 3 2 11 4 inf
Note
inf == Inf.
返回s true; however,南== NaN
总是返回false。
When vectorizing code, you often need to construct a matrix with a particular size or structure. Techniques exist for creating uniform matrices. For instance, you might need a 5-by-5 matrix of equal elements:
A = ones(5,5)*10;
v = 1:5; A = repmat(v,3,1)
A = 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
The functionrepmat
possesses flexibility in building matrices from smaller matrices or vectors.repmat
通过重复输入矩阵创建矩阵:
A = repmat(1:3,5,2) B = repmat([1 2; 3 4],2,2)
A = 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 B = 1 2 1 2 3 4 3 4 1 2 1 2 3 4 3 4
在许多应用中,在向量的元素上完成的计算取决于同一向量中的其他元素。例如,一个向量,x,可能代表一组。如何迭代一套没有a对于
orwhile
loop is not obvious. The process becomes much clearer and the syntax less cumbersome when you use vectorized code.
寻找矢量的冗余元素存在多种不同的方式。一种方式涉及该功能diff
。After sorting the vector elements, equal adjacent elements produce a zero entry when you use thediff
function on that vector. Becausediff(x)
生成一个较少元素的载体x
, you must add an element that is not equal to any other element in the set.南
always satisfies this condition. Finally, you can use logical indexing to choose the unique elements in the set:
x = [2 1 2 2 3 1 3 2 1 3]; x = sort(x); difference = diff([x,NaN]); y = x(difference~=0)
y = 1 2 3
unique
功能:Y =唯一(x);
unique
function might provide more functionality than is needed and slow down the execution of your code. Use thetic
andTOC.
功能如果要衡量每个代码片段的性能。
而不是仅仅返回集合或子集x
,您可以计算向量中的元素的发生。向量排序后,您可以使用find
函数确定零值的指标diff(x)
并展示元素改变值的位置。从后续指数之间的差异find
函数表示特定元素的出现次数:
x = [2 1 2 2 3 1 3 2 1 3]; x = sort(x); difference = diff([x,max(x)+1]); count = diff(find([1,difference])) y = x(find(difference))
count = 3 4 3 y = 1 2 3
find
function does not return indices for南
elements. You can count the number of南
andInf
values using theisnan
andisinf
functions.
count_nans = sum(isnan(x(:))); count_infs = sum(isinf(x(:)));
Function | 描述 |
---|---|
all |
Determine if all array elements are nonzero or true |
any |
Determine if any array elements are nonzero |
cumsum |
Cumulative sum |
diff |
Differences and Approximate Derivatives |
find |
查找非零元素的指数和值 |
ind2sub |
Subscripts from linear index |
我是 |
Inverse permute dimensions of N-D array |
logical |
Convert numeric values to logicals |
meshgrid. |
Rectangular grid in 2-D and 3-D space |
ndgrid |
N-D空间中的矩形网格 |
换乘 |
重新排列N-D阵列的尺寸 |
prod |
Product of array elements |
repmat |
Repeat copies of array |
reshape |
Reshape array |
shiftdim |
换档尺寸 |
sort |
排序数组元素 |
挤 |
Remove singleton dimensions |
sub2ind |
Convert subscripts to linear indices |
sum |
数组元素的总和 |