Professional Documents
Culture Documents
Matlab Note
Matlab Note
Array Operation
1. Colon notation: x=s:d:f
>>x=1:2:11
x=
1 3 5 7 9 11
>>x=1:2:10
x=
1 3 5 7 9
>> n = length(x)
n=
5
2.Creating equally spaced values: x=linspace(s,f,n)
d=(f-s)/(n-1)
for logarithmic scale: x=logspace(s,f,n)
>>x=logspace(1,7,7)
x=
>>x=logspace(1,3,3)
x=
10 100 1000
>> sumx=sum(x)
sumn =
1110
3. Accessing element:
>>X=[2,3,5,6];
>>X(end)
=6
When we add or subtract a scalar from a vector ,then scalar is added or subtracted
from each element of vector.
>>Z=x-1
=[1,2,4,5]
>>Z(2)
=2
>>Y=[-1,6,15,-7,31,2,-4,-5];
>>x=[Y(1),Y(2),Y(7),Y(8)]
x=
-1 6 -4 -5
>>ind =[1,2,7,8];
>>x=Y(ind)
x=
-1 6 -4 -5
4. Sorting
[ynew,index]=sort(y,’ascend’)
[ynew,index]=sort(y,’descend’)
x=
-1 6 -4 -5
>> [xnew,index]=sort(x,'ascend')
xnew =
-5 -4 -1 6
index =
4 3 1 2
>> [xnew,index]=sort(x,'descend')
xnew =
6 -1 -4 -5
index =
2 1 3 4
5. find (Relation)
Index=find(x<=0)
>> x=[-1,2,-3,4,5,6,-7];
>> index=find(x<=0)
index =
1 3 7
>> z=x(index)
z=
-1 -3 -7
6. Maximum/Minimum
[xmin,locmin]=min(x)
[Xmax,locmax]=max(x)
>> x=[-1,2,-3,4,5,6,-7];
>> max(x)
ans =
>> min(x)
ans =
-7
>> [xmax,locmax]=max(x)
xmax =
6
locmax =
Matrix Operation
1. Creation of matrix:
>>a=[1,2,3;3,4,5;5,6,7]
a=
1 2 3
3 4 5
5 6 7
a=
1 2 3
3 4 5
5 6 7
2. Order of matrix
[m,n]=size (a)
>>[m,n]=size (a)
m=
3
n=
3
3. Transpose: atr = a’ (apostrophe)
atr =
1 3 5
2 4 6
3 5 7
4. Special matrix
4 0 0
0 9 0
0 0 1
It also extracts diagonal elements from a given matrix.
>> a=[1,2,3,4;5,6,7,8;9,10,11,12;13,14,15,16]
a=
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
>> diag(a)
ans =
1
6
11
16
ans =
2
7
12
ans =
3
8
ans =
5
10
15
ans =
9
14
Z=magic(n≥3)
Z=magic(3)
z=
8 1 6
3 5 7
4 9 2
5.Min/Max in matrix
>>b=magic(4)
>>b=
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
>>maxb=max(b)
maxb=
4 2 3 1
>>max(max(b))
ans =
16
6. Matrix manipulation
A= [1,0,0;0,1,0;0,0,1]
U=[5 6 7]
V= [2;3;4]
A1=[A;U]
A2=[A V]
A3=[A u’]
8. Dot operations
Z1=X.*M
Z2=X./M
Z3=X.^M
>>X=1:8;
>>y=2.^X
y=
2 4 8 16 32 64 128 256
Or , x=linsolve(A,b)
8.Matrix operations:
det(A);inv(A);eig(A,B)
Anonymous Function and Symbolic Computation
>>f = @(x)x^3-3*x^2+x*log(x-1)+100
f=
@(x)x^3-3*x^2+x*log(x-1)+100
>> f(0)
ans =
100
>> f(1)
ans =
-Inf
Error in @(x)x^3-3*x^2+x*log(x-1)+100
f=
@(x)x.^3-3*x.^2+x.*log(x-1)+100
>> f(x)
ans =