Tutorial by Examples

MATLAB supports (and encourages) vectorized operations on vectors and matrices. For example, suppose we have A and B, two n-by-m matrices and we want C to be the element-wise product of the corresponding elements (i.e., C(i,j) = A(i,j)*B(i,j)). The un-vectorized way, using nested loops is as follo...
Given a random vector v = rand(10,1); if you want the sum of its elements, do NOT use a loop s = 0; for ii = 1:10 s = s + v(ii); end but use the vectorized capability of the sum() function s = sum(v); Functions like sum(), mean(), prod() and others, have the ability to operate ...
Quite often, the reason why code has been written in a for loop is to compute values from 'nearby' ones. The function bsxfun can often be used to do this in a more succinct fashion. For example, assume that you wish to perform a columnwise operation on the matrix B, subtracting the mean of each col...
MATLAB supports the use of logical masking in order to perform selection on a matrix without the use of for loops or if statements. A logical mask is defined as a matrix composed of only 1 and 0. For example: mask = [1 0 0; 0 1 0; 0 0 1]; is a logical matrix representing the identity matrix. ...
MATLAB R2016b featured a generalization of its scalar expansion1,2 mechanism, to also support certain element-wise operations between arrays of different sizes, as long as their dimension are compatible. The operators that support implicit expansion are1: Element-wise arithmetic operators: +, -,...
In many application it is necessary to compute the function of two or more arguments. Traditionally, we use for-loops. For example, if we need to calculate the f = exp(-x^2-y^2) (do not use this if you need fast simulations): % code1 x = -1.2:0.2:1.4; y = -2:0.25:3; for nx=1:lenght(x) for n...

Page 1 of 1