Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
MV_Eng_OTP(part1)_2013.doc
Скачиваний:
0
Добавлен:
01.04.2025
Размер:
1.3 Mб
Скачать

Switch and case

The switch statement executes groups of statements based on the value of a variable or expression. The keywords case and otherwise delineate the groups. Only the first matching case is executed. There must always be an end to match the switch.

The logic of the magic squares algorithm can also be described by

switch (rem(n,4)==0) + (rem(n,2)==0)

case 0

M = odd_magic(n)

case 1

M = single_even_magic(n)

case 2

M = double_even_magic(n)

otherwise

error('This is impossible')

end

Unlike the C language switch statement, MATLAB switch does not fall through. If the first case statement is true, the other case statements do not execute. So, break statements are not required.

for

The for loop repeats a group of statements a fixed, predetermined number of times. A matching end delineates the statements.

for n = 3:32

r(n) = rank(magic(n));

end

r

The semicolon terminating the inner statement suppresses repeated printing, and the r after the loop displays the final result.

It is a good idea to indent the loops for readability, especially when they are nested.

for i = 1:m

for j = 1:n

H(i,j) = 1/(i+j);

end

end

while

The while loop repeats a group of statements an indefinite number of times under control of a logical condition. A matching end delineates the statements.

Here is a complete program, illustrating while, if, else, and end, that uses interval bisection to find a zero of a polynomial.

a = 0; fa = -Inf;

b = 3; fb = Inf;

while b-a > eps*b

x = (a+b)/2;

fx = x^3-2*x-5;

if sign(fx) == sign(fa)

a = x; fa = fx;

else

b = x; fb = fx;

end

end

x

The result is a root of the polynomial x3 - 2x - 5, namely

x =

2.09455148154233

The cautions involving matrix comparisons that are discussed in the section on the if statement also apply to the while statement.

Continue

The continue statement passes control to the next iteration of the for or while loop in which it appears, skipping any remaining statements in the body of the loop. In nested loops, continue passes control to the next iteration of the for or while loop enclosing it.

break

The break statement lets you exit early from a for or while loop. In nested loops, break exits from the innermost loop only.

Here is an improvement on the example from the previous section. Why is this use of break a good idea?

a = 0; fa = -Inf;

b = 3; fb = Inf;

while b-a > eps*b

x = (a+b)/2;

fx = x^3-2*x-5;

if fx == 0

break

elseif sign(fx) == sign(fa)

a = x; fa = fx;

else

b = x; fb = fx;

end

end

1.3.4 Input and output of the information in a dialogue mode

For maintenance of interaction with the user in the course of M-file performance in system MatLab such functions are used:

disp (<a variable or the text in apostrophes>) – a conclusion of values of the specified variable or the specified text in a command window (examples are resulted in table 3.1);

x = input (‘ <inquiry> ’) - the target argument of this function is the value entered by the user from the keyboard in a command line in reply to inquiry;

Table 1.1 – function Examples disp

x =’Аргумент ’;

disp (x);

Conclusion of value of a text variable in a command window.

name =’Аргумент = ’; x=pi;

disp ([name num2str(x)]);

Conclusion of values of text variable and number variable in a command window.

x=10.5; y=sin (x); f=cos (x);

disp ([x y f]);

Conclusion of values of several numerical variables in a command window.

x = [-pi:0.1:pi]; y=sin (x); f=cos (x);

disp ([x ’ y ’ f ’]);

Conclusion of values of elements of files in the form of the table.

1.3.5 Organization of repetition of actions

One of the main tasks at independent creation of the program is returning maintenance to the beginning of the program for the purpose of continuation of its performance at new values of initial data.

Function is very convenient for the organisation of repetition of actions menu:

k=menu (‘ menu Heading ’, ’ the Name of 1st button ’, ’ the Name 2nd buttons ’, … ’ the Name of n th button ’) – function displays the menu. Program performance temporarily stops, and the system expects a choice of one of buttons. To target parametre k number of the pressed button is appropriated. Numbering of buttons begins with 1. Now, depending on value of parametre k it is possible to construct process of a branching of calculations.

Let the basic operators of the created program are located in above resulted function average.m. Then the scheme of maintenance of return to the beginning of performance of this function can be such:

% The Script-file which is an example for the organisation

% Repetitions of actions.

k=1;

while k == 1

x=input (‘ x = ‘);

z=average (x);

disp ([‘ average value = ’, num2str (z)]);

k=menu (‘ What to do? ’, …

‘ to Continue work ’, …

‘ to Finish work ’);

end

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]