What are good ways to write matlab code in matrix way?



Writing fast code in MATLAB is to let MATLAB do all the iteration over matrices all the time.

Anytime you are writing a "for loop" to iterate over all matrix elements, realize that MATLAB has a way of doing this for you and you just need to find it.

Here are the things to know:

  • If a variable in an expression is a matrix, MATLAB will do the looping automatically if it can figure out what you meant
  • Every built-in MATLAB function will take a matrix as well as a scalar. If you pass a matrix, it means "do this to each element of the matrix"
  • The iteration can span the equal sign of an assignment in certain cases
  • A subset of elements can be operated on using the binary "logical" data type or using "absolute indexing"
  • Every variable in MATLAB is actually a 2-dimensional matrix (or larger). To MATLAB, a scalar value is a 2-dimensional 1x1 matrix. A 1-dimensional vector is either a 1xN matrix or an Nx1 matrix.
  • Aggregating operations (e.g. sum, mean, min, max, std) operate on only 1 dimension of a 2D matrix X at a time. By default, they operate on dimension #1 unless X is a 1xN vector (then dimension #2 is used). However you can always specify which dimension you want used as a parameter. To operate on all elements as a giant vector, pass in X(:).

Here are some examples. Assume x, y, and z are a matrices (2 dimensional) or vectors (1 dimensional). All looping operations are done by MATLAB:

                x = zeros(n,m);          % initialize x to all zeros
x = ones(n,m) * 5;       % initialize all x to 5s
x(4,:) = 5;              % assign 5 to all elements of row #4
x(:,1) = x(:,1) + x(:,2);% add column #2 to column #1
y = x(2:5, 1:6);         % copy inner block rows 2-5 and columns 1-6 to y
z = x + y;               % add all elements of x and y, store in z
z = x * y;               % matrix multiply x and y, store in z
z = x .* y;              % individually multiply elements of x and y, store in z
z = x .^ 2;              % set each element of z to the same element of x squared
w = find(x == 5);        % search x for elements == 5, store integer indices in w
w = (x == 5);            % create binary matrix w that has a 1 anywhere x == 5
x(w) = 8;                % set value of all elements found above (either case) to 8
z = sum(x(:) < 1);         % count how many elements have value < 1
x(x < 0) = 0;            % set all negative elements of x to zero
y = mean(x, 1);          % set y(1,i) to the average of each column of x
y = mean(x(:));          % set y to the average of all elements of x
y = mean2(x);            % set y to the average of all elements of x (2D only)
x = [y, x];              % prepend columns of y to matrix x
x(:,end+1) = 5;          % add a column of 5s to the right side of x
z = sqrt(mean(x(:).^2)); % set z to the root-mean-square of all elements in x
if any(x(:) == 5)        % true if any element of x == 5
if all(x(:) == 0)        % true if all elements of x == 0
if any(all(x == 0, 2))   % true if any rows are all zeros
x = bsxfun(@times, x, 1./sum(x));   % normalize x so each column sums to 1
x = (x - min(x(:))) ./ (max(x(:)) - min(x(:))); % normalize x so min==0 and max==1