##### Efficient Matlab Coding

(This article is inspired by Omar's Article)

Most people programming at Matlab first get accustomed to some other programming languages like C, C++, Java or even Visual Basic. They learn tactics of manipulating arrays with loops. But as more and more loops are added to a program, the clumsier it gets. In Matlab also, the techniques learned at the previous mentioned languages can apply. But Matlab has some other advantages. In Matlab, every variable is a matrix. This gives some inherent advantages of matrix manipulation. In C, (and in C++ without having a custom class) you will not be able to do a matrix multiplication by simple A*B, in Matlab, you have a provision of doing so.

Ok let's start with some basic array operations. These may not be arcane secrets, still it's always good to know.

This one is useful if you are making a sine wave or other functions.

To make a unipolar signal bipolar:

Used to find index of elements satisfying some condition.

Use repmat() to tile matrix to form a larger version.

>> repmat(A, 3, 3)

ans =

1 2 3 1 2 3 1 2 3

A(i) = [] % Deletes the i-th element of a row/column vector A

Wanna make a 3x4 matrix a 2x6 Matrix?

use the reshape command

2 4

If you want to make only a vector,

B = A(:);

Warning: reshape, *ALWAYS* takes data from columns, and put them in column serially. You may get unexpected result, if, you want the data to be taken from rows instead. Try to transpose the matrix (

You may need to select the command window first to activate this.

http://blogs.mathworks.com/loren/2007/12/11/making-pretty-graphs/

http://blinkdagger.com/matlab/matlab-tips-and-tricks-on-creating-better-figures-and-plots

http://www.nada.kth.se/~hjorth/matlab/

Use the Kronecker Tensor Product function (kron),

1 1 1 2 2 2 3 3 3

B = A(ones(3,1),:)

*Example:

>> A =[1 2 3] % A is a row vector

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

>> B =

1 2 3

1 2 3

1 2 3

>> A = [1 ; 2 ; 3] % A as a column vector

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

>> B =

1 1 1

2 2 2

3 3 3

And WOW! it's really faster for replication in one dimension! For matrix A given above:

Elapsed time is 0.014354 seconds. %Using repmat()function

Elapsed time is 0.000063 seconds. %Using Tony's trick

Repeating Matlab row elements:

Based on the Tony's trick mentioned above, this is a program I've written for the 'time scaling' a matrix by repeating elements.

Most people programming at Matlab first get accustomed to some other programming languages like C, C++, Java or even Visual Basic. They learn tactics of manipulating arrays with loops. But as more and more loops are added to a program, the clumsier it gets. In Matlab also, the techniques learned at the previous mentioned languages can apply. But Matlab has some other advantages. In Matlab, every variable is a matrix. This gives some inherent advantages of matrix manipulation. In C, (and in C++ without having a custom class) you will not be able to do a matrix multiplication by simple A*B, in Matlab, you have a provision of doing so.

Ok let's start with some basic array operations. These may not be arcane secrets, still it's always good to know.

This one is useful if you are making a sine wave or other functions.

To make a unipolar signal bipolar:

Used to find index of elements satisfying some condition.

>> repmat(A, 3, 3)

1 2 3 1 2 3 1 2 3

A(i) = [] % Deletes the i-th element of a row/column vector A

Wanna make a 3x4 matrix a 2x6 Matrix?

use the reshape command

2 4

If you want to make only a vector,

B = A(:);

Warning: reshape, *ALWAYS* takes data from columns, and put them in column serially. You may get unexpected result, if, you want the data to be taken from rows instead. Try to transpose the matrix (

You may need to select the command window first to activate this.

http://blogs.mathworks.com/loren/2007/12/11/making-pretty-graphs/

http://blinkdagger.com/matlab/matlab-tips-and-tricks-on-creating-better-figures-and-plots

http://www.nada.kth.se/~hjorth/matlab/

Use the Kronecker Tensor Product function (kron),

1 1 1 2 2 2 3 3 3

B = A(ones(3,1),:)

*Example:

>> A =[1 2 3] % A is a row vector

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

>> B =

1 2 3

1 2 3

1 2 3

>> A = [1 ; 2 ; 3] % A as a column vector

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

>> B =

1 1 1

2 2 2

3 3 3

And WOW! it's really faster for replication in one dimension! For matrix A given above:

Elapsed time is 0.014354 seconds. %Using repmat()function

Elapsed time is 0.000063 seconds. %Using Tony's trick

Repeating Matlab row elements:

Based on the Tony's trick mentioned above, this is a program I've written for the 'time scaling' a matrix by repeating elements.

Most people programming at Matlab first get accustomed to some other programming languages like C, C++, Java or even Visual Basic. They learn tactics of manipulating arrays with loops. But as more and more loops are added to a program, the clumsier it gets. In Matlab also, the techniques learned at the previous mentioned languages can apply. But Matlab has some other advantages. In Matlab, every variable is a matrix. This gives some inherent advantages of matrix manipulation. In C, (and in C++ without having a custom class) you will not be able to do a matrix multiplication by simple A*B, in Matlab, you have a provision of doing so.

Ok let's start with some basic array operations. These may not be arcane secrets, still it's always good to know.

## Identity Matrix, Zero Matrix and Unity Matrix

```
n = 3;
A = eye (n); %creates n x n identity matrix
A = eye (n, 1); %creates n x 1 identity matrix
A = zeros(n); % creates n x n zero matrix (all elements zero)
A = ones(n); % creates n x n matrix (all elements one)
```

## A set of linearly increasing values

This one is useful if you are making a sine wave or other functions.

`linspace (initialvalue, finalvalue, number of samples)`

```
t = linspace (0, 2*pi, 1000); %creates linearly increasing array with values 0 to 2*pi
S = sin (t); % creates the sine wave
```

## Accessing a particular row or column

```
A(i,:) = 1 % makes all the elements of row i of matrix/vector A equal to 1.
A(:,i) = 1 % does the same thing with column 1.
B = A(i,:) % stores row i in a row vector B
```

## Accessing more than one rows/columns simultaneously

```
A = ([1,
A([i,j],:) = 1 % makes all elements of rows i and j equal to 1
B = A(:,[i,j])% B is a matrix with columns i and j of A as its two columns
```

## Swapping rows / columns

```
A([i,j],:) = A([j,i],:) % swaps the elements of rows i and j
A(:,[i,j]) = A(:,[j,i]) % swaps the column elements of col i and col j
```

## Replacing Values of A

To make a unipolar signal bipolar:

```
A = double(A); % required if the signal is of boolean type
A (A==0) = -1;
```

## The find( ) function

Used to find index of elements satisfying some condition.

```
find(A) % returns indices of all non-zero elements
find(A > 5) % finds indices of all elements greater than 5.
length(find(A==1)) %number of ones in A
```

## Inserting blank Rows / Columns:

```
A = [zeros(1,n-1); A]; % insert column
A = [A zeros(n,1)]; %insert Row
```

## Repeating or tiling a Matrix

Use repmat() to tile matrix to form a larger version.

A = [1 2 3; 4 5 6]

`A =`

` `

`1 2 3`

4 5 6

` `

>> repmat(A, 3, 3)

` `

ans =

` `

1 2 3 1 2 3 1 2 3

` 4 5 6 4 5 6 4 5 6`

1 2 3 1 2 3 1 2 3

4 5 6 4 5 6 4 5 6

1 2 3 1 2 3 1 2 3

4 5 6 4 5 6 4 5 6

## Deleting a row/column of a matrix

A(i) = [] % Deletes the i-th element of a row/column vector A

```
A(i,:) = [] % Deletes an entire row
A(:,i) = [] % Deletes an entire row
```

## Changing Size of Matrix

Wanna make a 3x4 matrix a 2x6 Matrix?

use the reshape command

A = [2 3 4 5; 6 7 8 9]

` `

`A =`

`2 3 4 5`

6 7 8 9

` `

`>> reshape (A, 4, 2)`

`ans =`

` `

2 4

` 6 8`

3 5

7 9

If you want to make only a vector,

B = A(:);

Warning: reshape, *ALWAYS* takes data from columns, and put them in column serially. You may get unexpected result, if, you want the data to be taken from rows instead. Try to transpose the matrix (

`A'`

) instead.## Ctrl+C. Break the running loop of Matlab.

You may need to select the command window first to activate this.

## Making Plots pretty

http://blogs.mathworks.com/loren/2007/12/11/making-pretty-graphs/

http://blinkdagger.com/matlab/matlab-tips-and-tricks-on-creating-better-figures-and-plots

http://www.nada.kth.se/~hjorth/matlab/

## Repeating Values of a Matrix

### Kronecker Tensor Product

Use the Kronecker Tensor Product function (kron),

`A = [1 2 3]`

`A =`

`1 2 3`

` >> kron (A, ones(1, 3))`

`ans =`

1 1 1 2 2 2 3 3 3

### Tony's Trick

This is a popular (and allegedly faster) trick used to form a matrix by repeating a row/column vector. (Courtesy of omar)

B = A(ones(3,1),:)

*Example:

>> A =[1 2 3] % A is a row vector

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

>> B =

1 2 3

1 2 3

1 2 3

>> A = [1 ; 2 ; 3] % A as a column vector

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

>> B =

1 1 1

2 2 2

3 3 3

And WOW! it's really faster for replication in one dimension! For matrix A given above:

Elapsed time is 0.014354 seconds. %Using repmat()function

Elapsed time is 0.000063 seconds. %Using Tony's trick

Repeating Matlab row elements:

Based on the Tony's trick mentioned above, this is a program I've written for the 'time scaling' a matrix by repeating elements.

```
%time scaling
function y = timescale (Mat, L)
[m, n] = size(Mat);
temp = zeros(m, n*L);
for i = 1:m
cur_row =Mat(i,:);
cur_row = cur_row (ones(1,L),:);
temp(i,:) = reshape(cur_row, 1, n*L);
end
y = temp;
end
```

(This article is inspired by Omar's Article)Most people programming at Matlab first get accustomed to some other programming languages like C, C++, Java or even Visual Basic. They learn tactics of manipulating arrays with loops. But as more and more loops are added to a program, the clumsier it gets. In Matlab also, the techniques learned at the previous mentioned languages can apply. But Matlab has some other advantages. In Matlab, every variable is a matrix. This gives some inherent advantages of matrix manipulation. In C, (and in C++ without having a custom class) you will not be able to do a matrix multiplication by simple A*B, in Matlab, you have a provision of doing so.

Ok let's start with some basic array operations. These may not be arcane secrets, still it's always good to know.

## Identity Matrix, Zero Matrix and Unity Matrix

```
n = 3;
A = eye (n); %creates n x n identity matrix
A = eye (n, 1); %creates n x 1 identity matrix
A = zeros(n); % creates n x n zero matrix (all elements zero)
A = ones(n); % creates n x n matrix (all elements one)
```

## A set of linearly increasing values

This one is useful if you are making a sine wave or other functions.

`linspace (initialvalue, finalvalue, number of samples)`

```
t = linspace (0, 2*pi, 1000); %creates linearly increasing array with values 0 to 2*pi
S = sin (t); % creates the sine wave
```

## Accessing a particular row or column

```
A(i,:) = 1 => makes all the elements of row i of matrix/vector A equal to 1.
A(:,i) = 1 => does the same thing with column 1.
B = A(i,:) => stores row i in a row vector B
```

## Accessing more than one rows/columns simultaneously

```
A = ([1,
A([i,j],:) = 1 => makes all elements of rows i and j equal to 1
B = A(:,[i,j])=> B is a matrix with columns i and j of A as its two columns
```

## Swapping rows / columns

```
A([i,j],:) = A([j,i],:) => swaps the elements of rows i and j
A(:,[i,j]) = A(:,[j,i]) => swaps the column elements of col i and col j
```

## Replacing Values of A

To make a unipolar signal bipolar:

```
A = double(A); % required if the signal is of boolean type
A (A==0) = -1;
```

## The find( ) function

Used to find index of elements satisfying some condition.

```
find(A) % returns indices of all non-zero elements
find(A > 5) % finds indices of all elements greater than 5.
length(find(A==1)) %number of ones in A
```

## Inserting blank Rows / Columns:

```
A = [zeros(1,n-1); A]; % insert column
A = [A zeros(n,1)]; %insert Row
```

## Repeating or tiling a Matrix

A = [1 2 3; 4 5 6]

`A =`

` `

`1 2 3`

4 5 6

` `

>> repmat(A, 3, 3)

` `

`ans =`

1 2 3 1 2 3 1 2 3

` 4 5 6 4 5 6 4 5 6`

1 2 3 1 2 3 1 2 3

4 5 6 4 5 6 4 5 6

1 2 3 1 2 3 1 2 3

4 5 6 4 5 6 4 5 6

## Deleting a row/column of a matrix

A(i) = [] % Deletes the i-th element of a row/column vector A

```
A(i,:) = [] % Deletes an entire row
A(:,i) = [] % Deletes an entire row
```

## Chaning Size of Matrix

Wanna make a 3x4 matrix a 2x6 Matrix?

use the reshape command

A = [2 3 4 5; 6 7 8 9]

` `

`A =`

`2 3 4 5`

6 7 8 9

` `

`>> reshape (A, 4, 2)`

`ans =`

` `

2 4

` 6 8`

3 5

7 9

If you want to make only a vector,

B = A(:);

Warning: reshape, *ALWAYS* takes data from columns, and put them in column serially. You may get unexpected result, if, you want the data to be taken from rows instead. Try to transpose the matrix (

`A'`

) instead.## Ctrl+C. Break the running loop of Matlab.

You may need to select the command window first to activate this.

## Making Plots pretty

http://blogs.mathworks.com/loren/2007/12/11/making-pretty-graphs/

http://blinkdagger.com/matlab/matlab-tips-and-tricks-on-creating-better-figures-and-plots

http://www.nada.kth.se/~hjorth/matlab/

## Repeating Values of a Matrix

### Kronecker Tensor Product

Use the Kronecker Tensor Product function (kron),

`A = [1 2 3]`

`A =`

`1 2 3`

`>> kron (A, ones(1, 3))`

`ans =`

1 1 1 2 2 2 3 3 3

### Tony's Trick

This is a popular (and allegedly faster) trick used to form a matrix by repeating a row/column vector. (Courtesy of omar)

B = A(ones(3,1),:)

*Example:

>> A =[1 2 3] % A is a row vector

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

>> B =

1 2 3

1 2 3

1 2 3

>> A = [1 ; 2 ; 3] % A as a column vector

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

>> B =

1 1 1

2 2 2

3 3 3

And WOW! it's really faster for replication in one dimension! For matrix A given above:

Elapsed time is 0.014354 seconds. %Using repmat()function

Elapsed time is 0.000063 seconds. %Using Tony's trick

Repeating Matlab row elements:

Based on the Tony's trick mentioned above, this is a program I've written for the 'time scaling' a matrix by repeating elements.

```
%time scaling
function y = timescale (Mat, L)
[m, n] = size(Mat);
temp = zeros(m, n*L);
for i = 1:m
cur_row =Mat(i,:);
cur_row = cur_row (ones(1,L),:);
temp(i,:) = reshape(cur_row, 1, n*L);
end
y = temp;
end
```

This collection is very smart and rich.

ReplyDeleteHoping for more useful tutorials.

Good one Sajid! You can add the diag( ) function as well. Courtesy of Wasim sir?

ReplyDeleteOk, I'll add the diag command soon.

ReplyDeletedear sir,

ReplyDeleteplease kindly give me these informations:

can u inform me how to get matlab?

what books/websites needed to be expert in matlab?

what books/websites needed to be adroit in

ac ckt?

thank u.

Matlab is a commercial software, and licensing information can be found in the website of MathWorks: http://www.mathworks.com/

ReplyDeleteTo be expert in any programming language, you need to practice and solve lots of problems.... Try searchi ng for online tutorials on Matlab, and solving basic problems