Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Lab_MATLAB_English_Part2.doc
Скачиваний:
2
Добавлен:
19.11.2019
Размер:
421.89 Кб
Скачать

31

Міністерство освіти і науки, молоді та спорту україни

Запорізький національний технічний університет

Laboratory Works of Programming in

MATLAB

Part 2

Методичні вказівки до лабораторних робіт з дисципліни

«Обчислювальна техніка та програмування»

для студентів з англійською мовою навчання

денної форми навчання

2012

Laboratory Works of Programming in MATLAB. Part 2. Методичні вказівки до лабораторних робіт з дисципліни «Обчислювальна техніка та програмування» для студентів з англійською мовою навчання денної форми навчання. / Укл. Н.І. Біла, О.В. Кривцун - Запоріжжя: ЗНТУ, 2012. - 46 с.

Містить завдання до лабораторних робот та приклади виконання за темою “Програмування в середовищі MATLAB”, що вивчається в курсі “Обчислювальна техніка та програмування” у другому модулі студентами електротехнічних спеціальностей з англійською мовою навчання.

Укладачі: Біла Н.І. доцент

Кривцун О.В., ст.викладач

Рецензенти: Пінчук В.П., доцент,

Нагорний Ю.І., доцент

Відповідальний за випуск Корніч Г.В., зав.кафедрою

Затверджено на засіданні кафедри

обчислювальної математики,

протокол № від

Рекомендовано до видання НМО спеціальності як методичні вказівки до лабораторних робот з дісципліни “Обчислювальна техніка та програмування” для студентів з англійською мовою навчання.

Contents

1 Laboratory work №1. The loop statements in matlab programs

1.1 Loop Statements ………………………4

1.2 Tasks for laboratory work ………………………………..9

1.3 Example of performance of laboratory work ……………13

1.4 The test questions ………………………..........14

2 Laboratory work №2. The work with arrays in matlab

2.1 Arrays ……………………………….15

2.2 Tasks for laboratory work ………………………………18

2.3 Examples of performance of laboratory work ………….19

2.4 Test questions ………………………...................23

3 Laboratory work №3. The work with matrixes in matlab

3.1 Multidimensional Arrays ………………………………..24

3.2 Tasks for laboratory work ……………………………….25

3.3 Examples of performance of laboratory work …………..29

4 The List of Books …………………………46

1 Laboratory work № 1 Loop statements in mAtlab programs

1.1 Loop Statements

Loop structures allow you to execute one or more lines of code repetitively. The loop structures that MatLab supports include:

· For...

·While...

For... Loop

When you know how many times you need to execute the statements in the loop a For… loop is a better choice. Unlike a While loop, a For loop uses a variable called a counter that increases or decreases in value during each repetition of the loop.

The syntax is:

for counter= initial_value:increment:final_value

ACTION 1;

ACTION 2;

...

ACTION N;

end

The arguments counter, initial_value, final_value, and increment are all numeric.

The increment argument can be either positive or negative. If increment is positive, start must be less than or equal to end or the statements in the loop will not execute. If increment is negative, start must be greater than or equal to end for the body of the loop to execute. If Step isn't set, then increment defaults to 1.

In executing the For loop, MatLab:

1. Sets counter equal to initial_value.

2. Tests to see if counter is greater than final_value. If so, MatLab exits the loop. (If increment is negative, MatLab tests to see if counter is less than final_value.)

3. Executes the actions.

4. Increments counter by 1 or by increment, if it's specified.

5. Repeats steps 2 through 4.

For example, if we want to calculate square roots of odd integers between 1 and 25 and output the table:

for i = 1:2:25

Sq = sqrt(i);

disp([i Sq])

end

Use break statement to break the execution of the loop.

For example,

for x=0:0.1:3.14

y = cos(x);

disp([x y])

if y < 0

break

end

end

This loop finished it work when variable y stands less then zero.

FOR loops are also quite time consuming. It is usually better in MATLAB to deal with the vector dot-operations as defined earlier.

Example 1.1. This code calculates the sum : for given integer n.

function s=s_sum(n)

s=0;

for i = 1: n

s = s+1/( i^2+1);

end

Nested Control Structures

You can place control structures inside other control structures (such as an if... block within a for... loop). A control structure placed inside another control structure is said to be nested. Control structures in MatLab can be nested to as many levels as you want. It's common practice to make nested decision structures and loop structures more readable by indenting the body of the decision structure or loop.

Example 1.2. This procedure calculates and outputs the table of powers of integer value k.

Figure 1.1 – Window of text editor with script

Notice that the first end closes the inner for loop and the last end closes the outer for loop. Likewise, in nested if statements, the end statements automatically apply to the nearest prior if statement.

You can see on figure 1.1 that MatLab moves nested loops on the right and marks the beginning and end of the loops.

The main rule for nested structures is: structure which first is started has to be last ended. The amount of repetitions of statements inside of two loops is equal the production repetitions of first loop and repetitions of second loop. So, on result of performing script on figure 1.1 you can see 50 numbers (10 * 5).

While…loop

While loops work well when you don’t know how many times you need to execute the statements in the loop. Use a While loop statement to execute a block of statements an indefinite number of times. Statement evaluates a numeric condition to determine whether to continue execution. As with if…statement, the condition must be a value or expression that evaluates to False (zero) or to True (nonzero).

In the following While…loop, the statements execute as long as the condition is True:

While condition statements

end

When MatLab executes this While loop, it first tests condition. If condition is False (zero), it skips past all the statements. If it’s True (nonzero), MatLab executes the statements and then goes back to the While statement and tests the condition again.

Example 1.3. We want to know the number of positive integer that we need to sum up before reaching a given number x. The following function accomplishes this task:

Figure 1.2 – Function for example 1.3

with the following usage (for x = 1000):

>> test7(1000)

ans = 45

Consequently, the loop can execute any number of times, as long as condition is nonzero or True. The statements never execute if condition is initially False.

MATLAB allows the user to insert breakpoints within loops to terminate it (it by might useful for example if convergence is not achieved. The prototype within a while loop would be the following:

WHILE CONDITION1 is TRUE

ACTION1...N

IF CONDITION2 is TRUE

BREAK

END

END

Use of the break point can be avoid by using CONDITION1 and CONDITION2 in the WHILE STATEMENT:

WHILE CONDITION1 is TRUE AND CONDITION2 is FALSE

ACTION1...N

END

This will cause to terminate the loop whenever the condition 2 is met even if condition 1 is not.

Example 1.4. The sequence

is given. To calculate the limit of this sequence for given a with given accuracy .

This sequence is known as Euclid algorithm from Ancient Greek. It tendencies to . This sequence is converging, therefore distance between xk and xk+1 became less and less when k grows. So, we will stop calculations when inequality carries out for some k. We do not need to keep all elements of the sequence in memory during calculation. It is enough to have two near by elements. Let call it x_previous and x_next.

Function for example 1.4

function x=exmpl1_4(a,eps)

% calculate the limit of sequence

% which tendencies to square root from a

k=0; % amount of iterations

x_previous=a;

x_next=(x_previous + a / x_previous)/2;

d=abs(x_previous - x_next);

% in loop are performed less than 100 iterations

while d>eps & k<100

x_previous = x_next;

x_next = (x_previous + a / x_previous)/2;

d = abs(x_previous - x_next);

k=k+1;

end

x=x_next;

Function calls give the following results:

>> x=exmpl1_4(10,0.001)

x = 3.1623

>> y=sqrt(10) % Checking the program

y = 3.1623

>> x=exmpl1_4(121,0.001)

x = 11.0000

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