# MATLAB

## Overview

Much of the conversion from MATLAB-based code can be accomplished with search-and-replace, but a number of constructions require more care. The biggest change will be using accessor functions in place of parentheses to extract and update elements from matrices. Example functions in the library include ml_matrix::sub_matrix(), ml_matrix::get_row(), and ml_matrix::get_col(). Another important feature is the use of member functions in the library, which greatly increases the efficiency of the function but may require more lines of code than the MATLAB version. For example, the rand function can be used in a single step in MATLAB, but it exists in the library only as a member function, so you must first create the matrix of the desired size on one line, and then call ml_matrix::ones() on it. Another such matrix creation function is ml_matrix::identity(). The MATLAB zeros is not needed at all since matrices are initialized with zeros by default, as in x = ml_matrix(3,3).

In general, many functions are equivalent and most algebraic operations can be written using MatrixLib with the same syntax as in MATLAB. All functions in the library use a lowercase convention with underscores separating words. Array of matrix indices can be input and output from MatrixLib functions using the pss int array class.

In the examples below, a is used to indicate a matrix, v indicates a one-dimensional matrix or vector, i and j indicate arrays of integers, d indicates a double-precision number, m and n indicate integers, r indicates a 2 x n matrix with (row, column) index pairs, a z indicates a 3 x n matrix with an element value and its (row, column) indices.

 Common MATLAB Functions and MatrixLib Equivalents Function Library Function Description Module zeros(3,3) ml_matrix a(3,3); Create a matrix of zeros Construction and I/O ones(2) ml_matrix a(2,2,1.0); Create a matrix of ones Construction and I/O disp(a) a.display("a"); Display the matrix in human readable form Construction and I/O eye(3) ml_matrix a(3,3); a.identity(); Create an identity matrix. Matrix Manipulation sin(a) a.sin(); Sine of the elements of a Trigonometric Functions inv(a) a.inv(); Matrix inverse Linear Algebra [U,S,V] = svd(x) S = svd(U, V, x); Singular value decomposition Linear Algebra c = dot(a,b) d = a.dot(b); Vector dot product Linear Algebra i = find(a == 1) r = a.find(ML_EQUAL_TO, 1.0); Find indices based on a numeric comparison Inspection and Assignment [m,n] = size(a) m = a.rows(); n = a.cols(); Determine the size of a matrix Inspection and Assignment [b,i] = sort(a) a.sort(); r = a.sort_indices(); Ascending sort Inspection and Assignment [b,i] = min(a) z = a.min(); Smallest element, returns a double Returns an integer Inspection and Assignment b = sum(a,1) b = a.sum_cols() Sum of elements, columnwise Inspection and Assignment b = sum(a,2) b = a.sum_rows() Sum of elements, rowwise Inspection and Assignment isempty(x) a.is_empty(); Determine if a matrix is empty Inspection and Assignment

Here are some equivalents for common operations in MATLAB:

 Common MATLAB Operations and MatrixLib Equivalents Operator Library Call Description Module a' a.transpose(); Matrix transpose. LinearAlgebra a^n a.mpow(n); Matrix powers Linear Algebra a.*b dotstar(a,b); Element-by-element multiplication Arithmetic Operators a./b dotslash(a,b); Element-by-element division Arithmetic Operators c = a + b c(a); c += b; Element-by-element addition Arithmetic Operators a.^n a.dotpow(n); Element-by-element powers Algebraic Functions 1:0.1:10 colon(1,0.1,10) Create an incremented array Construction and IO a = [b c] a = append(b,c) Append two matrices (horizontal concatenation) Matrix Manipulation a = [b; c] a = stack(b,c) Stack two matrices (vertical concatenation) Matrix Manipulation a(:,k) = v a.inc_cols(v,k,k) Assign a column of a matrix Matrix Manipulation b = a(1:3,1:3) b = a.sub_matrix(1,3,1,3) Extract a contiguous submatrix Matrix Manipulation b = a(:,k) b = a.get_col(k) Extract a single column. Matrix Manipulation a(1) d = a(3,1) d = a.get(3,1); a.get(1,1); Extract a single element of a matrix; returns an error if the indices are out-of-bounds. Matrix Manipulation a(end+1,1) = d a(4,1) = d; Assign an element of a matrix, resizes if necessary. Matrix Manipulation

There are numerous ways to create matrices and populate them with numbers. Some are member functions which operate on existing matrices without changing their size, such as ml_matrix::ones() and ml_matrix::identity(). To create a matrix from a set of numbers, you can either use a string representation - the easiest, but least efficient way to convert from MATLAB - or create an array of doubles.

Consider the MATLAB expression,

```
a = [1 2 3; 4 5 6; 7 8 9];
```

In the preferred method, you first create an array, and then pass that array to the matrix constructor:

```
double v[9] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0};
ml_matrix a(3,3,v);
```

You can also create the matrix from a string matching the MATLAB format:

```
ml_matrix a("[1 2 3; 4 5 6; 7 8 9]");
```

Matrices can also be initialized from a file and from a binary format.

## Examples

These examples are taken from PSS' Spacecraft Control Toolbox, a MATLAB toolbox for control system analysis and design.

Consider first a function which converts a vector from one frame to another, in this case the Cartesian x-y-z frame to a spherical frame. The two versions look like this:

MATLAB:

```
function [r, theta, phi] = Cart2Sph(x, y, z)```

```r = sqrt(x.^2 + y.^2 + z.^2);
theta = atan2(y, x);
phi = acos(z./r);
```

C++:

```
void cart_to_sph(const pss_matrix &x, const pss_matrix &y, const pss_matrix &z, pss_matrix &r, pss_matrix &theta, pss_matrix &phi)
{
r = sqrt(pow(x,2) + pow(y,2) + pow(z,2));
theta = atan2(y, x);
phi = acos(dotslash(z,r));
return;
}
```

The power operators are simply replaced by the pow() function, the atan2() and sqrt() function calls are the same, and the . operator is replaced by the corresponding function. Also observe that the inputs are passed in as const matrices while the outputs are passed in as pointers.

The next example we review returns the unit vector portion of a quaternion, a 4-element mathematical representation of an orientation. The MATLAB version returns both the unit vector and the angle which comprise the quaternion calculation.

```
function [angle, u] = Q2AU(q)```

```angle = 2*atan2(-Mag(q(2:4)), q(1));
if (angle < -pi)
angle = angle + 2*pi;
elseif (angle > pi)
angle = angle - 2*pi;
end```

```if (norm(q(2:4)) < eps)
u = [1;0;0];
else
u = Unit(q(2:4));
end
```

The C++ version of the vector portion of this function demonstrates the double array constructor, a sub_matrix() call, and compounded member function calls.

```
pss_matrix q_to_vec(const pss_matrix &quaternion)
{
double unit_array[3] = {1.0,0.0,0.0};
pss_matrix unit_vec(3,1,unit_array);
const double eps = 1.e-10;
if (quaternion.sub_matrix(2,4,1,1).vmag() >= eps)
{
unit_vec = quaternion.sub_matrix(2,4,1,1).unit();
}
return unit_vec;
}
```