Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Одиноков / МиИПиС_асп_13г / MATLAB_R2013a_Выбор.doc
Скачиваний:
32
Добавлен:
15.04.2015
Размер:
4.03 Mб
Скачать

Example 2 — Varying Data Values Stored in a Function Handle

Values stored within a handle to a nested function do not have to remain constant. The following function constructs and returns a function handle h to the anonymous function addOne. In addition to associating the handle with addOne, MATLAB also stores the initial value of x in the function handle:

function h = counter

x = 0;

h = @addOne;

function y = addOne;

x = x + 1;

y = x;

end

end

The addOne function that is associated with handle h increments variable x each time you call it. This modifies the value of the variable stored in the function handle:

h = counter; % Создание function handle @addOne в counter. Ответ: h = @counter/addOne; путь counter/addOne и x=0 хранятся в h.

h() % Первый handle-вызов addOne для расчетов y при x=0 (хранится в h); другие операции в counter, кроме addOne, не выполняются.

ans =

1 (x=x+1=0+1=1; новое значение x сохранится в памяти addOne и в h)

h() % Второй вызов addOne для расчетов y уже при x=1;

ans =

2

Example 3 — You Cannot Vary Data in a Handle to an Anonymous Function

Unlike the example above, values stored within a handle to an anonymous function do remain constant. Construct a handle to an anonymous function that just returns the value of x, and initialize x to 300. The value of x within the function handle remains constant regardless of how you modify x external to the handle:

x = 300; % Сохранение x в главной памяти.

h = @()x; % Создание h при x=300. Код функции (y=x) и x=300 теперь будут сохраняться в h независимо от изменения значения x в общей

% памяти.

x = 50; % Изменение прежнего и сохранение нового значения x в главной памяти.

h() % Вызов h без входного параметра, ответ соответствует коду функции y=x при прежнем значении x:

ans =

300

clear x % Удаление x из главной памяти.

h() % Повторный вызов h без входного параметра, поэтому как и в предыдущем случае

ans =

300

ДОПОЛНЕНИЕ. Другой пример:

a=2;

h=@(x)a*x;

h(3)

ans =

6

clear a;

h(3)

ans =

6 (Конец ДОПОЛНЕНИЯ)

Call Functions Outside of Their Normal Scope

By design, only functions within a program file are permitted to access local functions defined within that file. However, if, in this same file, you were to construct a function handle for one of the internal local functions, and then pass that handle to a variable that exists outside of the file, access to that local function would be essentially unlimited. By capturing the access to the local function in a function handle, and then making that handle available to functions external to the file (or to the command line), the example extends that scope. An example of this is shown in the preceding section, Capture Data Values For Later Use By a Function (R2013a>MATLAB>Language Fundamentals>Data Types>Function Handles>Applications of Function Handles).

Private functions also have specific access rules that limit their availability with the MATLAB environment. But, as with local functions, MATLAB allows you to construct a handle for a private function. Therefore, you can call it by means of that handle from any location or even from the MATLAB command line, should it be necessary.

Save the Handle in a mat-File for Use in a Later matlab Session

If you have one or more function handles that you would like to reuse in a later MATLAB session, you can store them in a MAT-file using the save function and then use load later on to restore them to your MATLAB workspace.