Arrays and Metrices:
- Variable for one dimensional vector should be start with lowercase.
- Variable for two dimensional vector (matrix) should be start with Uppercase.
- Scalars is one by one matrices.
- Not like java or ruby, the first element of an array in Matlab is indexed by number 1
- Let say x is a 3x3 matrix.
X(2,2)
return the element from second row and second column. If you want to change the value, simply assign a new value.X(2,2) = 5
- If a variable XYZ doesn't exist and you type in a command
XYZ(2,2) = 3
Matlab will give you 2x2 matrix with XYZ(2,2) equals to 3 and rest elements of 0 X(2,[1 3])
gives you the 1st and the 3rd elements of the second row of a matrix.X([1 2],2)
gives you the 1st and the 2nd elements of the second column of a matrix.- For matrix multiplication the inner dimension muss be equal. 5x3 matrix * 3x4 matrix works just fine. but 5x3 matrix * 2x4 matrix gives you an error.
- Use
randi( maxNumber , numberOfRow , numberOfColumn)
to create a random matrix of integers - let say X is a matrix.
X^2
meansX*X
or matrix multiplication. andX.^2
means to square each element of X. AndX.^Y
means to tell Matlab to exponentiate each element of X to the power of element of Y of the same index. - Use
find(A);
to find all non zero elements of matrix A. The output of this function is a vector containing linear indices of each non zero elements in matrix A
Elements with index: 1, 3, 5 and 7 are not zero |
Operators:
- Colon ':' operator:
x = 1 : 3 : 7
means we tell Matlab to create row vector start from 1 increment it by 3 till its maximum of 7. it will give you a resultx = 1 4 7
- Colon operator is very useful to create an array of odd or even numbers
1:2:7
will return an array of odd numbers[1, 3, 5, 7]
- Colon operator can also give you an array in a decreasing order.
10:-3:1
will return[10, 7, 4, 1]
ints = 1 : 10
means give me an array of numbers from one to tenA * B
ormtimes(A,B)
means matrix A times matrix B.A .* B
ortimes(A,B)
More operator can be found in Matlab Operators
size(variable)
gives you the size of a matrix. e.g.x = [3 2 4 ; 2 5 6]
andsize(x)
gives youans = 2 3
matrix of 2 rows and 3 columns- Any scalar for. e.g.
x = 2
andsize(x)
gives youans = 1 1
since in Matlab scalar is one by one matrix. - Some operators can also be written as a function:
plus(1,2)
means1+2 ans = 3
andcolon(1,7)
gives you[1, 2, 3, 4, 5, 6, 7]
Function handles
Function handles are Variables that allow you to invoke a function indirectly. Using function handles you can pass a function as a parameter of another function. For example I have a functionf(x)=3x^4 - 2x^2
And we want to pass this function to another function like this:
Now if you try to call the function using
diffQuotF(f, x0, h)
you'll get an error message.
The right way to pass the ' f ' function as a parameter is by using the @ (at) sign before the ' f '. like this:
No comments:
Post a Comment