0% found this document useful (0 votes)
3 views7 pages

Example Matlab

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views7 pages

Example Matlab

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

EXAMPLE

MATLAB
1-If x=[1 4; 8 3], find :
a) the inverse matrix of x .
b) the diagonal of x.
c) the sum of each column and the sum of whole matrix x.
d) the transpose of x.
ANSWER
a- b- c-
>>x=[1 4 ;8 3] >>diag(x) >>sum(x)
X = ans= ans =
1 4 1 9 7
8 3 3
>>inv(x) d- >>sum(sum(x))
ans= >>x’ ans=
-0.1034 0.1379 ans =
0.2759 -0.0345 1 8
4 3
2-If x= [2 8 5; 9 7 1], b=[2 4 5] find:
a) find the maximum and minimum of x.
b) find mean value over each row of x.
c) add the vector b as a third row to x.
ANSWER
a- b- c-
>>x=[2 8 5 ;9 7 1] >>mean(x,2) >>b=[ 2 4 5];
X = ans= >>x_new =[x ;b]
2 8 5 5 x_new=
9 7 1 5.6667 2 8 5
>>max(x(:)) 9 7 1
ans= 2 4 5
9 or >> x(3,:)=b;
>>min(x(:)) or >> x(3,1:3)=b ;
ans= or >>x(3,1:end)=b;
1
3-If x=[ 2 6 12; 15 6 3; 10 11 1], then
a) replace the first row elements of matrix x with its average value.
b) reshape this matrix into row vector.
ANSWER
a- b-
>>x=[2 6 12 ;15 6 3 ;10 11 1] >>reshape(x’ ,1,[])
X = ans=
2 6 12 2 6 12 15 6 3 10 11 1
15 6 3
10 11 1
>>x(1,:) =mean(x(1,:))
ans=
6.6667 6.6667 6.6667
15.0000 6.0000 3.0000
10.0000 11.0000 1.0000
4-Generate a 4 x 4 Identity matrix.
ANSWER
>>I = eye(4)
I =
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
5-Generate the following row vector b=[5, 10, 15, 20 . . . . . . . . . 95, 100], then find the number of elements
in this vector.
ANSWER
>>b= 5:5:100;
>>length(b)
ans =
20
6-Generate the following row vector b=[1, 2, 3, 4, 5, . . . . . . . . . 9,10], then transpose it to column vector.
ANSWER
>>b=1:10;
>>b’;
7-if x = [1,5,7,9,13,20,6,7,8], then
a) replace the first five elements of vector x with its maximum value.
b) reshape this vector into a 3 x 3 matrix..
ANSWER
a- b-
>>x=[1 5 7 9 13 20 6 7 8] >>y(1,:)=x(1:3);
X = >>y(2,:)=x(4:6);
1 5 7 9 13 20 6 7 8 >>y(3,:)=x(7: 9);
>>x(1:5) =max(x) >>y
ans= ans =
20 20 20 20 20 20 6 7 8 1 5 7
9 13 20
6 7 8
8- Find the factorial of 5
>> x=2:5; or >>factorial(5)
>> prod(x) ans =
120
randi Function in MATLAB
The randi function in MATLAB is used to generate random integer values from a specified range.
▪ Generate a single random integer:
>>r = randi(10) % Random integer between 1 and 10
r=
9
▪ Generate an m × n matrix of random integers:
>>R = randi(10, 3, 4) % 3x4 matrix with random integers between 1 and 10
R=
10 7 6 2
2 1 10 10
10 3 10 10
▪ Generate numbers within a specific range [a, b]:
>>R = randi([5, 15], 2, 3) % 2x3 matrix with integers between 5 and 15
R=
10 6 15
13 9 13

You might also like