Logical Data Type

A logical scalar variable, stored in a single byte, can hold one of two values: true or false. Note that true and false are two special MATLAB functions. If a mixture of logical and numeric values are found in an expression, then true converts to 1 and false converts to 0., or vice versa.

Logical Expressions

A logical expression is one that evaluates to either true or false. A logical expression may contain relational operators and/or logic operators as well as arithmetic operators.

Relational Operators

GREATER THAN
>= / GREATER THAN OR EQUAL TO
LESS THAN
<= / LESS THAN OR EQUAL TO
== / EQUAL TO
~= / NOT EQUAL TO

The arithmetic operators have higher precedence than (are performed before) relational operators.

The comparison of two numericvalues is obvious, and the comparison of two strings of equal length is according to character-by-character comparison, and character comparison is based on the character’s order in the UNICODE table. Note that the answer is a logical array of n values, where n shows the number of characters in the two strings.

Examples

> a=true;

> b=34~=34.0

b =

0

> c=b==false

c =

1

> d=43==43

d =

1

> e=1+2>=6/2

e =

1

> disp(a)

1

> f=[-2 3 1;1 -1 -3]

f =

-2 3 1

1 -1 -3

> g=f>0

g =

0 1 1

1 0 0

> h=f>g

h =

0 1 0

0 0 0

> k='A';

> l='9';

> m='A9';

> n='B9';

> k>l

ans =

1

> m<n

ans =

1  0

> oo=0;

> pp=sin(pi);

> qq=oo==pp

qq =

0

> rr=abs(oo-pp)<eps

rr =

1

Logic Operators

AND
AND / With shortcut; Scalars only
| / OR
|| / OR / With shortcut; Scalars only
xor / XOR
~ / NOT
A / B / ~B / A & B
A&B / A || B
A | B / xor (A,B)
false / false / true / false / false / false
false / true / false / false / true / true
true / false / true / false / true / true
true / true / false / true / true / false

The above is the truth table for the logical operators.

The order of precedence rule states that first the arithmetic operations are performed, then relational operations are performed, then logic operations are performed according to the following rules:

  1. First, ~ is performed,
  2. Then, and operations are performed,
  3. Finally, or operations / exclusive or functions are performed.
  4. The order of evaluation is left to right for equal precedence.

The operators & and | work for matrices of equal size only.

Samples

> n1=true;

> n2=false;

> n3=0;

> n4=6;

> n5=-4;

> n6=[0 -2;1 3];

> n7=[false false;true true];

> ~n1

ans =

0

> ~n3

ans =

1

> ~n4

ans =

0

> n3 | n2

ans =

0

> n4 & n6

ans =

0 1

1 1

> xor(n5,n3)

ans =

1

> n6 | n7

ans =

0 1

1 1

> ~n7 & n3 | xor(n6,n7)

ans =

0 1

0  0

MATLAB Logical functions

Function

/

Purpose

ischar(a)

/

Returns true if a is a character array and false otherwise

isempty(a)

/

Returns true if a is an empty array, [] and false otherwise

isinf(a)

/

Returns true if a is infinite, Inf and false otherwise

isnan(a)

/

Returns true if a is not a number, NaN and false otherwise

isnumeric(a)

/

Returns true if a is a numeric array and false otherwise

logical(a)

/

Converts numerical values to logical values: if a is a value other than 0, then the result is true; if a is 0, then the result is false

if Statements

An if statement indicates a selection in the flow of commands based on a condition. In all the formats that follow a condition is any logical expression, which evaluates to either true (1) or false (0).

if (condition)

statement1;

statement2;

end

When the execution flow of the code reaches to that if statement, the condition is evaluated. If the condition is true, then the block of statements (statement1; statement2;…) is executed. The execution flow continues with the next statement following the if. If the condition is false, the execution flow continues with the next statement.

This concept may be visualized by the flowchart symbols as follows:

Sample1

>ii = 2; jj= 3;k = 4;

>if (ii==jj); k=5; end

% the condition is false so k is still 4

>jj=2;

>if (k==4); ii=3;end

% the condition is true so ii is 3 now

> disp(k)

4

> disp(jj)

2

> disp(ii)

3

Sample 2

I = 0;k = 3;n = 9366;

if ( rem(n,k) == 0)

fprintf('%d is divisible by %d',n,k);

% 9366 is divisible by 3

k = k + 1;

% 4

I = k + 4;

% 8

end

n = 9991;

if (condition) true_statement_1; true_statement_2; . . true_statement_n;else false_statement_1; false_statement_2; . . false_statement_k;end

In this format, there are extra statements labeled false_statement_1 through false_statement_k to be executed when the condition evaluates to false! The statements labeled true_statement_1 through true_statement_n are executed when the condition evaluates to true.

if (condition1)

block1_statement1;

block1_statement2;

elseif (condition2) can be used

block2_statement1; as many times as

block2_statement2; required

end

In this format,

  1. condition1 is evaluated. If it is true (non-zero), then the statements in block1 are executed. If condition1 is false (zero), then
  2. condition2 is evaluated. If it is true, then the statements in block2 are executed. If condition2 is false, then
  3. condition3 is evaluated…. Until all conditions are exhausted.
  4. if all conditions are false, execution of the program continues with the next statement.

The general format of an if statement is then:

if (condition1)

block1_statement1;

block1_statement2;

elseif (condition2) can be used

block2_statement1; as many times as

block2_statement2; required

else false_statement_1;

false_statement_2;

.

.

false_statement_k;

end

The difference of this format from the previous one is:

4.  if all conditions are false, execute the statements in the false block.

Sample program 1

Write a program that reads in a number and outputs reasonable messages depending on the divisibility of the number by 3.

Solution 1

%input

num = input ('Enter a number :') ;

%process

isDiv3 = mod(num,3) == 0;

%output

fprintf('%d',num);

if (isDiv3)

fprintf(' is divisible by 3.');

else

fprintf(' isnot divisible by 3.');

end

Sample Program 2

Write a program that test if an input integer is even or odd and outputs appropriate messages.

Solution 2
%input
num = input ('Enter a number :') ;
%process
isEven = mod(num,2) == 0;
%output
fprintf('%d',num);
if (isEven)

fprintf(' is an even number.');

else

fprintf(' is an odd number.');

end

Sample Program 3

Write a program which reads in a number and outputs appropriate messages according to 3 cases: number is positive, number is 0, number is negative.

Solution 3

%input

num = input ('Enter a number :') ;

%process and output

fprintf('%d',num);

if (num>0)

fprintf(' is a positive number.');

elseif (num==0)

fprintf(' is zero');

else

fprintf(' is a negative number.');

end

Sample Program 4

Write a program which determines if a given year is a leap year or not and displays a proper message.

Solution 4

%input

year = input ('Enter a year (4-digits) :') ;

%process

isLeap=((rem(year,4) == 0) & (rem(year,100) ~= 0)) || (rem(year,400) == 0) ;

%output

fprintf('%d',year);

if (isLeap)

fprintf(' is a leap year.');

else

fprintf(' is not a leap year.');

end

Sample Program 5

Write a MATLAB program which computes the monthly payments of a given loan for a given annual interest rate and a given period in years. Use the formula below to compute the payment:

loan . monthly interest rate

payment = ------

1

1 ------

(1+monthly interest rate) number of months

Note that all the input should be positive and the rate should be less than 100%.

Solution 5

% get the inputs

loanAmount = input ('Enter the amount of loan : ' ) ;

annualInterestRate = input ('Enter annual interest rate : ' ) ;

numOfYears = input ('Enter number of years : ') ;

% validate data

if (loanAmount>0 & numOfYears>0 & annualInterestRate>0 & … annualInterestRate<100)

% compute monthly payment!

monthlyInterestRate = annualInterestRate / 1200

monthlyPayment = loanAmount* monthlyInterestRate / ...

(1-1/(1+monthlyInterestRate)^ (numOfYears*12));

% display the result on the screen

fprintf('The montly payment is %5.2f',monthlyPayment);

else

fprintf('You have entered invalid numbers');

end

Sample Program 6

In geometry, let a, b, and c denote the side lengths and h denote the height of a perpendicular triangle.

Then the following is true:

c2 = a2 + b2 Þ c = Square root of ( a2+b2 )

and the area can either be calculated as ab/2 or ch/2, which means

a b = c h Þ h = a * b / c

Type a MATLAB program so that

· the user will type a and b. Note that both a and b must be positive.

· the program will computethe values of c and h.

· the program must display the value of c and h

Solution 6

a= input ('Enter the value for side a:');

b = input('Enter the value for side b:');

if ( a > 0 & b > 0 )

c = sqrt(a*a+b*b) ;

h = a*b/c ;

fprintf('The value of c is %f',c);

fprintf('The value of h is %f',h);

else

fprintf('You must type positive values for a and b');

end

Sample Program 7

Write a program to compute an employee's weekly pay. Employees are paid at a baserate for the first 40 hours they work each week. Hours over 40are paid at an overtime rate equal to twice the base rate, except for part-time employees who are never paid overtime.

1) The user enters the employee type, hourly rate, and the number ofhours worked.

2) The program computes and displays the employee's pay.

Solution 7

%Read the employee type, hourly rate, and hours worked

employeeType = input ('Enter type of employee (1 full-time, 2 part-time): ');

hourlyRate = input ('Enter the hourly rate (double): ');

hoursWorked =input ('Enter the hours worked (int) : ');

%Calculate the weekly pay

if (hoursWorked <= 40 || employeeType == 2)

weeklyPay = hourlyRate * hoursWorked;

else

weeklyPay = hourlyRate * 40 + hourlyRate * 2 * (hoursWorked - 40);

end

%Print the weekly pay

fprintf ('The weekly pay is $ %5.2f',weeklyPay);

Sample Program 8

Revise sample program 7 so that the program does not ask for the employee type, hourly rate, and hours worked of a single employee, but sets these data for 4 employees as follows:

1st employee / 2nd employee / 3rd employee / 4th employee
Employee type / 1 / 2 / 2 / 1
Hourly rate / $4 / $5 / $4 / $5
Hours worked / 32 / 16 / 41 / 41

Investigate the following solution and note the differences.

Solution 8

%Define the employee type, hourly rate, and hours worked

employeeType = [ 1 2 2 1 ];

hourlyRate = [4 5 4 5];

hoursWorked =[32 16 41 41];

%Calculate the weekly pay

employee=1

if (hoursWorked(employee) <= 40 | employeeType(employee) == 2)

weeklyPay(employee) = hourlyRate(employee) * hoursWorked(employee)

else

weeklyPay(employee) = hourlyRate(employee) * 40 + hourlyRate(employee)* 2 * (hoursWorked(employee) - 40)

end

employee=2

if (hoursWorked(employee) <= 40 | employeeType(employee) == 2)

weeklyPay(employee) = hourlyRate(employee) * hoursWorked(employee)

else

weeklyPay(employee) = hourlyRate(employee) * 40 + hourlyRate(employee)* 2 * (hoursWorked(employee) - 40)

end

employee=3

if (hoursWorked(employee) <= 40 | employeeType(employee) == 2)

weeklyPay(employee) = hourlyRate(employee) * hoursWorked(employee)

else

weeklyPay(employee) = hourlyRate(employee) * 40 + hourlyRate(employee)* 2 * (hoursWorked(employee) - 40)

end

employee=4

if (hoursWorked(employee) <= 40 | employeeType(employee) == 2)

weeklyPay(employee) = hourlyRate(employee) * hoursWorked(employee)

else

weeklyPay(employee) = hourlyRate(employee) * 40 + hourlyRate(employee)* 2 * (hoursWorked(employee) - 40)

end

%Print the weekly pay

fprintf ('%s',['The weekly pay for the 4 workers are ' num2str(weeklyPay)]);