Professional Documents
Culture Documents
Lecture 3
Relational operators
There are six relational operators in MATLAB:
Operator Description
< Less than
=< Less than or equal to
> Greater than
=> Greater than or equal to
== Equal to
=~ Not equal to
Relational operators
Sample Code
Operator Meaning Sample Code
Result
== equal to ]6 5 4 3 2[ == ]5 1 4 1 3[ ]0 0 1 0 0[
=~ not equal to ]6 5 4 3 2[ =~ ]5 1 4 1 3[ ]1 1 0 1 1[
Logical operators
Operator Description
EX:
n= -7 ;
if n < 0 % If n negative, display error message.
disp('Input must be positive');
elseif rem(n,2) == 0 % If n positive and even, divide by 2.
A = n/2;
else
A = (n+1)/2; % If n positive and odd, increment and divide.
end
If Statement
Write the program that display the result according to the degree:
degree=23;
if degree<50
disp(‘Fail');
else
disp(‘Pass');
end
If Statement
x=[ 1 -1 2 3];
max=x(1);
for i=1:length(x)
if x(i) > max
max=x(i);
end
end
max
If Statement
calculate the maximum and minimum value in matrix x
x=[ 1 -1 2 3];
max=x(1);
min=x(1);
for i=1:length(x)
if x(i) < min
min=x(i);
end
if x(i) > max
max=x(i);
end
end
fprintf('Max. number is : %d \n',max)
fprintf('Min. number is : %d \n',min)
If Statement
Write a Matlab program that have two input integers x and y. It will output
the absolute difference of the two integers.
x=4;
y=2;
Result=0;
if x<y
Result = y-x;
elseif x>y
Result = x-y;
else
Result=0;
end
disp(Result)
If Statement
Determine and print the number of zeros in matrix x
x=[0 1 -1 0 2 0 3];
count = 0;
for i=1: length(x)
if x(i)==0
count=count+1;
end
end
disp(count);
If Statement
x=[ 1 -1 2 3];
for i=1:length(x)
if x(i)<0
disp('Matrix has negative element');
end
end
If Statement
Percentage marks attained by a student in three exams are to be entered to
a computer. An indication of Pass or Fail is given out after the three marks
are entered. The criteria for passing are as follows:
A student passes if all three examinations are passed. Additionally a
student may pass if any subject is failed and the overall average is greater
than or equal to 50. The pass mark for an individual subject is 40.
ExamResult1=45;
ExamResult2=50;
ExamResult3=35;
Average = (ExamResult1+ ExamResult2+ ExamResult3)/3;
if ExamResult1>=40 && ExamResult2>= 40 && ExamResult3>=40
disp('pass');
elseif Average >=50
disp('pass');
else
disp('fail');
end