• 沒有找到結果。

Logical Functions

N/A
N/A
Protected

Academic year: 2022

Share "Logical Functions"

Copied!
31
0
0

加載中.... (立即查看全文)

全文

(1)

Logical Functions

NaN: Not A Number, caused by the math operation like ∞

∞ and ∞ − ∞.1

1SeeNaN.

Zheng-Liang Lu 93 / 123

(2)

Conditional Statements

Matlab conditional statements enable us to write programs that make decisions.

Conditional statements contain one or more of theif,else, andelseif statements.

The endstatement denotes the end of a conditional statement.

(3)

Example: if-else

If x is a nonnegative real number, then y =√ x .

input(prompt) gives the user the prompt (in string) and then waits for numeric input from the keyboard.

1 clear; clc;

2 % main

3 x = input('Enter a number? '); % input from keyboard

4 if x >= 0

5 y = sqrt(x) % show y

6 else

7 disp([num2str(x),' is a negative number.']);

8 end

Note that one ifshould be paired with oneend.

input(prompt, ’s’) waits for astring input.

Zheng-Liang Lu 95 / 123

(4)

Exercise: Nested Conditional Statements

1 clear; clc;

2 x = input('Enter x?', 's');

3 % Contribution by Mr. Curtis Yen (MAT24506) on ...

Sep. 10, 2014.

4 w = str2num(x);

5 if isempty(w) % w is not empty if w is a number

6 disp('It is not a number.');

7 else

8 if w >= 0

9 y = sqrt(w)

10 else

11 disp([x ' is not a positive real number.']);

12 end

13 end

(5)

Example: if-elseif-else

1 clear; clc;

2 % main

3 x = input('Enter any real number: ');

4 if isempty(x)

5 disp('No input.')

6 elseif x >= 0

7 disp('It is a positive number.')

8 else

9 disp('It is a negative number.')

10 end

Zheng-Liang Lu 97 / 123

(6)

Example: Centesimal-to-GPA Problem

2

Write a program which converts centesimal points to GPA.

Let x be the input grade.

For example,

If 90 ≤ x ≤ 100, then x is converted to A.

If 80 ≤ x < 90, then B.

If 70 ≤ x < 80, then C.

If 60 ≤ x < 70, then D.

If x < 60, then F.

(7)

1 clear; clc;

2 x = input('Enter points? ');

3 if x >= 90

4 disp('A');

5 elseif x >= 80

6 disp('B');

7 elseif x >= 70

8 disp('C');

9 elseif x >= 60

10 disp('D');

11 else

12 disp('F');

13 end

Can we reverse the conditions?

Can we place the conditions at your will? (Two levels.)

Zheng-Liang Lu 99 / 123

(8)

Exercise: Do you want to continue?

Write a program which allows the user to type either Y, y, or by pressing the Enter key as default value to print “Yes.”

If typing N or n, print “No.”

Print “Invalid input.” if any other response.

(9)

1 clear all;

2 clc;

3 % main

4 x=input('Continue? [Y/N]','s');

5 if isempty(x) | | (x=='Y' | | x=='y')

6 disp('Yes');

7 elseif (x=='N' | | x=='n')

8 disp('No');

9 else

10 disp('Invalid input.');

11 end

3Note that logical operators cannot be applied to empty sets, so putting isempty(response) in the first place is a better way.

3Contribution by Mr. Grant Huang (MAT24217) on July 23, 2014.

Zheng-Liang Lu 101 / 123

(10)

Alternative: switch/case

switch/case structure is often used when a series of programming path options exists for a given variable, depending on its value.

The code is a bit easier to read with switch/case

arrangement, a structure that allows you to choose between multiple outcomes, based on specific criterion.

(11)

Example

1 clear all;

2 clc

3 % main

4 disp('Welcome to Taiwan. I can show you the ...

ticket price.')

5 disp('You can choose Taipei, Taichung, or Tainan.')

6 city = input('Enter the name of a city: ','s');

7 switch city

8 case 'Taipei'

9 disp('Price: $100')

10 case 'Taichung'

11 disp('Price: $200')

12 case 'Tainan'

13 disp('Price: $300')

14 otherwise

15 disp('Not an option.') % default

16 end

Zheng-Liang Lu 103 / 123

(12)

Example

4

: Switch/Case Replaced by If

1 ...

2 if strcmp(city,'Taipei')

3 disp('Price: $100');

4 elseif strcmp(city,'Taichung')

5 disp('Price: $200');

6 elseif strcmp(city,'Tainan')

7 disp('Price: $300');

8 else

9 disp('Not in the list.');

10 end

Can you implement strcmp function on your own?

What is the significant difference between ifandswitch?

switch: cases by enumeration

(13)

Error Handling

You can use a try-catchstatement to execute code after your program encounters an error.

try-catchcan be useful if you:

want to finish the program in another way that avoids errors;

need to clean up unwanted side effects of the error;

1 try

2 try block; % normal execution code

3 catch

4 catch block; % error handling section

5 end

lasterr returns the last error message.

Zheng-Liang Lu 105 / 123

(14)

Example: Combinations

For all nonnegative integers n ≥ k, nk is given by

n k



= n!

k!(n − k)!. Note that factorial(n) returns n!.

1 clear; clc;

2 % main

3 n = input('n = ? ');

4 k = input('k = ? ');

5 if n >= 0 && k >= 0

6 y = factorial(n) / (factorial(k) * ...

factorial(n - k))

7 else

8 disp('Invalid inputs.')

9 end

(15)

Try n = 2, k = 5.

factorial(−3) is not allowed!

1 clear; clc;

2 % main

3 n = input('n = ?');

4 k = input('k = ?');

5 if n >= 0 && k >= 0

6 try

7 y = factorial(n) / (factorial(k) * ...

factorial(n - k))

8 catch

9 lasterr

10 y = factorial(k) / (factorial(n) * ...

factorial(k - n))

11 end

12 else

13 disp('Invalid inputs.')

14 end

Zheng-Liang Lu 107 / 123

(16)

Repetition Structures

As a rule of thumb, if a section of code is repeated more than three times, it is a good candidate for a repetition structure.

Repetition structures are often called loops.

All loops consist of 5 basic parts:

A parameter to be used in determining whether or not to end the loop.

Initialization of this parameter.

A way to change the parameter each time through the loop.5 A comparison, using the parameter, to a criterion used to decide when to end the loop.

Calculations to do inside the loop.

(17)

MATLAB supports two different types of loops: the for loop and the whileloop.

break,continue, andreturn can be used in the loopifsome condition meets.

break: to end the loop even when the loop does not finish.

continue: to pass the loop once.

return: to end the subroutine (function).

Zheng-Liang Lu 109 / 123

(18)

for Loops

A forloop is the easiest choice when you know how many times you need to repeat the loop.

1 for loop variable

2 statements

3 end

(19)

Zheng-Liang Lu 111 / 123

(20)

Example: for Loop

1 clear; clc;

2 % main

3 for i = 0 : 1 : 10

4 i

5 end

1 clear; clc;

2 % main

3 for i = {'Arthur', 'Ruth'}

4 i

5 end

(21)

Example: Find Maximum

Write a program which returns the maximum element in the input list.

Recall the algorithm discussed in the first class.

1 clear; clc;

2 % main

3 x = [4 9 7 2 -1 6 3];

4 max = x(1);

5 for i = 2 : 7

6 if max < x(i)

7 max = x(i);

8 end

9 end

10 max

Zheng-Liang Lu 113 / 123

(22)

Exercise: Running Sum

1 clear; clc;

2 % main

3 x = [60, 70, 80, 90, 100];

4 y = 0;

5 for i = 1 : 1 : 5

6 y = y + x(i); % running sum

7 end

8 y

Use length(x) instead of 5 in Line 6.

Then the for loop will do as many times as the element numbers of x .

(23)

while Loops

whileloops are the easiest choice when you need to keep repeating the instructions until a criterionwhich is written in logical expression is not met.

1 while criterion

2 statements

3 end

Note that beforewhile, the criterion will be checked.

Can you replace a whileloop with a for loop? (Try.)

Zheng-Liang Lu 115 / 123

(24)
(25)

Example

Write a program to determine the number of terms required for the sum of the series 5k2− 2k, k ∈ N, to exceed 104. What is the sum for this many terms?

Note that N = {1, 2, · · · }.

The series is 3, 16, 39, · · · .

Zheng-Liang Lu 117 / 123

(26)

Solution

1 clear; clc'

2 % main

3 s = 0;

4 k = 0;

5 while s < 1e4

6 k = k + 1;

7 s = s + 5*kˆ2 - 2*k;

8 end

9 k % show k

10 s % check the sum

We don’t know how many terms we need to add into the sum in advance.

Fortunately, “the sum exceeds 104” is the criteria in this case.

(27)

Example: A Simple Infinite Loop

1 while 1

2 fprintf('Press ctrl+c to stop me!!!!\n');

3 end

In line 2, fprintf shows a string on the screen.

Besides, ’\n’ is used to create a new line.

Note that your can stop your program by pressingctrl+c.

Zheng-Liang Lu 119 / 123

(28)

Example: Infinite Loop by for?

1 clear; clc;

2 % main

3 for i = 0 : inf % inf = infinity

4 disp('I am running...');

5 end

1 Warning: FOR loop index is too large. Truncating ...

to 2147483647.

2 > In test 20140605 1 at 5

3 Elapsed time is 62.910073 seconds.

I cannot run an infinite loop using afor loop on my desktop6.

(29)

Midpoint break Loops

Midpoint break loops are useful for situations where the commands in the loop must be executed at least once, but where the decision to make anearlytermination is based on some criterion.

A breakstatement will cause termination of the smallest enclosing whileor forloop.

Zheng-Liang Lu 121 / 123

(30)

Example: PRIMES problem

7

Let x be any positive integer larger than 2 as input.

Then x is aprime number if for all y ∈ {2, 3, . . . , x − 1}, y is not a divisor of x , denoted by y - x.

In other words, x is called a compositenumber if

∃y ∈ {2, 3, . . . , x − 1}, y | x.

So, how to write a program that determines if the input number x is a prime?

You may use mod(a, b) to calculate the remainder of a dividing by b.

(31)

1 clear; clc;

2 x = input('Enter a positive integer? ');

3 for i = 2 : 1 : x - 1

4 if mod(x, i) == 0

5 disp('This is not a prime.');

6 break;

7 end

8 end

Can we reduce the number of elements to check?

Zheng-Liang Lu 123 / 123

參考文獻

相關文件

The proof is based on Hida’s ideas in [Hid04a], where Hida provided a general strategy to study the problem of the non-vanishing of Hecke L-values modulo p via a study on the

Now, nearly all of the current flows through wire S since it has a much lower resistance than the light bulb. The light bulb does not glow because the current flowing through it

(a) The magnitude of the gravitational force exerted by the planet on an object of mass m at its surface is given by F = GmM / R 2 , where M is the mass of the planet and R is

If the skyrmion number changes at some point of time.... there must be a singular point

where L is lower triangular and U is upper triangular, then the operation counts can be reduced to O(2n 2 )!.. The results are shown in the following table... 113) in

The case where all the ρ s are equal to identity shows that this is not true in general (in this case the irreducible representations are lines, and we have an infinity of ways

Let and be constants, let be a function, and let be defined on the nonnegative integers by the recu rrence. where we interpret to mean either

 “A manager of a school shall, at least once in every 12 months, make to the incorporated management committee of the school a written declaration which (a) states the particulars