In: Computer Science
8. In MATLAB, the colon operator can be used in two ways: creating a matrix (or array) and selecting part(s) of a matrix (or array). Explain and give examples of each.
9. For a matrix C, that has 10 rows and 12 columns:
- What is the MATLAB command to select all of row 5 from it?
- What 2 MATLAB commands would ask the user for an integer, N, from 1 to 10 and then create an array D which is just row N from matrix C?
10. For matrix D, that has 5 rows and 8 columns:
- What does the MATLAB command Z=sum(D) do and what is the size (or dimensions) of Z?
(8)
In Matlab, colon operator can be used in two
ways:
Way 1: Creating a matrix(or
array)
1. Statement a:b
creates a vector from a to b.
2. Statement a:k:b
creates a vector from a to b at an increment of k
Example: Creating a matrix of dimension
3x5
>> m = [1:5 ; 6:10 ;
11:15]
m =
1 2 3
4 5
6 7 8
9 10
11
12 13 14 15
>>
Way 2: Selecting parts of
array
mat(:,j)
-> Returns j th column.
mat(i,:)
-> Returns i th row.
mat(:,:)
-> Returns entire matrix.
>> m(:,:)
ans =
1 2 3
4 5
6 7 8
9 10
11
12 13 14 15
>>
>> m(1,:)
ans =
1 2 3 4 5
>> m(:,4)
ans =
4
9
14
_____________________________________________________________________________________________________________________
(9)
Creating a sample matrix C, that has 10 rows
and 12 columns:
>> C = randi(10,10,12);
MATLAB command to select all of row 5 from it:
C(5,:)
Fetches entire fifth row
Two MATLAB commands would ask the user for an integer,
N, from 1 to 10 and then create an array D which is just row N from
matrix C:
Asking user for integer N:
N = input(' Enter N value (1 to 10) :
');
Creating an array D which is just row N from
matrix C:
D = C(N,:)
_____________________________________________________________________________________________________________________
(10)
Creating a sample matrix D, that has 5 rows
and 8 columns:
>> D = randi(10,5,8);
Command Z=sum(D); calculates sum of each column values
in array D and stores the result as column in Z.
Size (or dimension) of Z can be found using command
size(Z); which returns 1 row and 8 columns.