Professional Documents
Culture Documents
Lecture 2
Lecture 2
Lecture 2
MATLAB
LECTURE 2
How to input a number from a
user?
My_number=input(‘enter any number’)
How to take a string from a user?
My_string=input(‘enter your name’, ‘s’)
How to simply display?
A NUMBER/vector/matrix:
disp(x)
or disp([1 2 3 3 0])
A STRING
disp(‘hi! How are you’)
or disp(mystr)
Where mystr= ‘hi! How are you’
Defining vectors- using colon operator
CONSIDER COLUMN
CONSIDER ROW 1
NUMBER 1 TO 3
147
EXCERCISE
MAKE ANY 4X3 MATRIX AND ACCESS ITS
ELEMENTS FROM COLUMN 2 AND 3 THAT
LIE WITHIN ROW 3 AND 4
size() & length()
Mathematical operations
+
*
/
-
In Matlab, these operators work the same way for a
matrix as they do for real numbers.
However if you want to add/subtract etc two vectors
element wise then use a dot before the operator, like this:
.*, .^ etc
Concatenating a matrix
m1 =
1 2
4 5
3 7
m2 =
70 0
5 0
6 4
m3 =
70 0
5 0
6 4
Concatenating a matrix
>>new_matrix=[m1 m2 m3]===concencates these
three matrices row wise
>> [m1 m2 m3]
ans =
70 0 70 0 70 0
5 0 5 0 5 0
6 4 6 4 6 4
Concatenating a matrix
>>new_matrix=[m1; m2; m3]===concencates these three matrices column wise
>> [m1; m2; m3]
ans =
70 0
5 0
6 4
70 0
5 0
6 4
70 0
5 0
6 4
Transpose()
Transposing a matrix
matrixx =
1 2 3
4 5 5
6 7 8
To take transpose, just type
>> matrixx'
ans =
1 4 6
2 5 7
3 5 8
Addition and Subtraction
Addition and Subtraction
Element-Wise Functions
Operators: element-wise
Operators: standard
Exercise: Vector Operations
Overwriting a row or column
Suppose you want to overwrite the ith column of a
matrix A,
>>A(:, i)=[1; 3; 6]
Similarly, to overwrite a row:
A(i, :)=[1 3 6]
Just be sure that the number of elements in rows/
columns is in accordance with the dimensions of
the matrix!!
While loop
Keeps on repeating a block of code until a specified
condition is met. E.g
X=1;
While x<=100
X=x+1;
end
FIND COMMAND
TRY THIS
>>vec=[1 67 13 7 45 89];
What is the difference between these two
commands:
>>a=find(vec==13)
>> [a b] = find (vec==13)
ALSO TRY THIS……
Matt=[1 2 3 4 5 5 5 5 5 5 5]
J=find(Matt==5)
See J in the workspace.
How do I know the total number of times that 5
occurs in the matrix?
Random numbers
>>rand %random decimal no between 0 and 1
>>quit