Upload
aswin-pv
View
73
Download
1
Tags:
Embed Size (px)
DESCRIPTION
Basic matlab operators
Citation preview
Matlab basics ,operators & branching statements
Basics commands
• Inputting a variableNum = input(‘ Enter a number ’);• Displaying output data– Use of semicolon– X=a+b;– X=a+b output displays automatically
• disp(‘Hello’)
Relational operators
• Equality ==• Not equal ~=• >• <• >=• <=
Equality operator ==
• Difference between ‘=‘ & ‘==‘• A=5; B=5; C=-35;• A==B 1• A==C 0• Q=[1 2 3]; W=[2 3 4] ; R=[1 9 3] ; T=[1 2 3];• Q==W ?• Q==T ?• Use of isequal()
Not equality ~=
• A=89;• B=79;• C=89;• A==B ??• A~=B ??• A~=C ??
> ,< , >= ,<=
• A=12 ; B=87 ; C=78;• A>B • A<B
• Q=[1 2 3 8 9 4] R=[2 3 1 8 9 2]• Q>R• Q<R
Logic operators
• Logical AND &• Logical AND with shortcut evaluation &&• Logical OR |• Logical OR with shortcut evaluation ||• Logical XOR xor(a,b)• Logical NOT ~
Logical AND &a b Y=a & b
0 0 ?
0 1 ?
1 0 ?
1 1 ?
Truth tablea b Y=a & b
0 0 0
0 1 0
1 0 0
1 1 1
A = 1;B=0;A & B ?
A=8;B=-9;
A & B ?
Logical AND with shortcut evaluation &&
• Support partial evaluations• A = 0 ;• B= 1;• A & B • A && B
Problem
• Test whether ratio of two variables a and b is greater than 10
• X = a/b >10 ; • What if b = 0?• Use shortcut evaluations• x = (b ~= 0) && (a/b > 10)
Logical OR |a b Y=a |b
0 0 ?
0 1 ?
1 0 ?
1 1 ?
Truth tablea b Y=a | b
0 0 1
0 1 1
1 0 1
1 1 0
A = 1;B=0;A | B ?
A=8;B=-9;
A | B ?
Logical XOR xor(a,b)a b Y= xor ( a ,b)
0 0 ?
0 1 ?
1 0 ?
1 1 ?
Truth table
a b Y=xor ( a , b)
0 0 0
0 1 1
1 0 1
1 1 0
A = 1;B=0;xor ( A , B) ?
A=8;B=-9;
xor ( A, B) ?
Logical NOT ~
• One operand only• A=1; ~A ??• B= false ~B ??• C=-89 ~C ??
Logical functions
• isequal(a,b) • ischar(a) • isempty(a)• isinf(a)• isnan(a)• isnumeric(a)• logical(a)
A=‘brainbitz’; C=-89; D=[1 2 -3 0 1 ];B=15; E =[ ]; F=0; H = [1 2 3 4]; J=[1 2 3] ; G =[ 0 0 0];
• ischar(A) • ischar(C)• isempty(F)• isempty(E )• isempty(G)• isinf(C)• isinf(C/F)• isnumeric(D) • logical (D) [1 1 1 0 1];
Branching statements & Loops
• If• Switch• While • For• Try catch branch
If statement
if (condition 1)-------------------------------
elseif (condition 2)------------------------------
else---------------------
end
Switchswitch (expression)case val1
--------------------
case val2---------------
otherwise-------------------
end
while
while (expression)------------------------------------end
For
for index=1:increment:m-----------------------------------end
Try/catch
try----------------------------
catch------------------------------
end
Problem
• Input 2 numbers and calculate factorial of their differences , ie (N1 – N2)!
N1=input(‘Enter number 1 ‘);N2=input(‘Enter number 2 ’ );Result = factorial(N1 – N2);OutputsN1=5 ;N2=2;Result =3!
=6
N1=2;N2=5;Result = -3 ! = ERROR !!!
Continued…
N1=input(‘Enter number 1’);N2=input(‘Enter Number 2’);try
Result = factorial( N1 - N2 );
catchResult = factorial( N2 - N1 );
end