Using MATLAB (779505), страница 74

Файл №779505 Using MATLAB (Using MATLAB) 74 страницаUsing MATLAB (779505) страница 742017-12-27СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 74)

In this case, many M-files must be parsed before the applicationbecomes visible.Another situation for pcode is when, for proprietary reasons, you want to hidealgorithms you’ve created in your M-file.17-1317M-File ProgrammingHow MATLAB Passes Function ArgumentsFrom the programmer’s perspective, MATLAB appears to pass all functionarguments by value. Actually, however, MATLAB passes by value only thosearguments that a function modifies. If a function does not alter an argumentbut simply uses it in a computation, MATLAB passes the argument byreference to optimize memory use.Function WorkspacesEach M-file function has an area of memory, separate from MATLAB’s baseworkspace, in which it operates. This area is called the function workspace,with each function having its own workspace context.While using MATLAB, the only variables you can access are those in the callingcontext, be it the base workspace or that of another function.

The variables thatyou pass to a function must be in the calling context, and the function returnsits output arguments to the calling workspace context. You can however, definevariables as global variables explicitly, allowing more than one workspacecontext to access them.Checking the Number of Function ArgumentsThe nargin and nargout functions let you determine how many input andoutput arguments a function is called with. You can then use conditionalstatements to perform different tasks depending on the number of arguments.For example,function c = testarg1(a,b)if (nargin == 1)c = a.^2;elseif (nargin == 2)c = a + b;endGiven a single input argument, this function squares the input value.

Giventwo inputs, it adds them together.Here’s a more advanced example that finds the first token in a character string.A token is a set of characters delimited by whitespace or some other character.Given one input, the function assumes a default delimiter of whitespace; giventwo, it lets you specify another delimiter if desired. It also allows for twopossible output argument lists.17-14Functionsfunction [token,remainder] = strtok(string,delimiters)% Function requires at least one input argumentif nargin < 1error('Not enough input arguments.');endtoken = []; remainder = [];len = length(string);if len == 0returnend% If one input, use white space delimiterif (nargin == 1)delimiters = [9:13 32]; % White space charactersendi = 1;% Determine where non-delimiter characters beginwhile (any(string(i) == delimiters))i = i + 1;if (i > len), return, endend% Find where token endsstart = i;while (~any(string(i) == delimiters))i = i + 1;if (i > len), break, endendfinish = i – 1;token = string(start:finish);% For two output arguments, count characters after% first delimiter (remainder)if (nargout == 2)remainder = string(finish + 1:end);endThe strtok function is a MATLAB M-file in the strfun directory.17-1517M-File ProgrammingNote The order in which output arguments appear in the functiondeclaration line is important.

The argument that the function returns in mostcases appears first in the list. Additional, optional arguments are appended tothe list.Passing Variable Numbers of ArgumentsThe varargin and varargout functions let you pass any number of inputs orreturn any number of outputs to a function. This section describes how to usethese functions and also covers:• “Unpacking varargin Contents”• “Packing varargout Contents”• “varargin and varargout in Argument Lists”MATLAB packs all specified input arguments into a cell array, a special kindof MATLAB array that consists of cells instead of array elements.

Each cell canhold any size or kind of data – one might hold a vector of numeric data, anotherin the same array might hold an array of string data, and so on. For outputarguments, your function code must pack them into a cell array so thatMATLAB can return the arguments to the caller.Here’s an example function that accepts any number of two-element vectorsand draws a line to connect them.function testvar(varargin)for k = 1:length(varargin)x(k) = varargin{k}(1); % Cell array indexingy(k) = varargin{k}(2);endxmin = min(0,min(x));ymin = min(0,min(y));axis([xmin fix(max(x))+3 ymin fix(max(y))+3])plot(x,y)17-16FunctionsCoded this way, the testvar function works with various input lists; forexample,testvar([2 3],[1 5],[4 8],[6 5],[4 2],[2 3])testvar([–1 0],[3 –5],[4 2],[1 1])Unpacking varargin ContentsBecause varargin contains all the input arguments in a cell array, it’snecessary to use cell array indexing to extract the data.

For example,y(i) = varargin{i}(2);Cell array indexing has two subscript components:• The cell indexing expression, in curly braces• The contents indexing expression(s), in parenthesesIn the code above, the indexing expression {i} accesses the i’th cell ofvarargin. The expression (2) represents the second element of the cellcontents.Packing varargout ContentsWhen allowing any number of output arguments, you must pack all of theoutput into the varargout cell array.

Use nargout to determine how manyoutput arguments the function is called with. For example, this code accepts atwo-column input array, where the first column represents a set of xcoordinates and the second represents y coordinates. It breaks the array intoseparate [xi yi] vectors that you can pass into the testvar function on theprevious page.function [varargout] = testvar2(arrayin)for k = 1:nargoutvarargout{k} = arrayin(k,:) % Cell array assignmentendThe assignment statement inside the for loop uses cell array assignmentsyntax. The left side of the statement, the cell array, is indexed using curlybraces to indicate that the data goes inside a cell. For complete information oncell array assignment, see the “Structures and Cell Arrays“ section.17-1717M-File ProgrammingHere’s how to call testvar2.a = {1 2;3 4;5 6;7 8;9 0};[p1,p2,p3,p4,p5] = testvar2(a);varargin and varargout in Argument Listsvarargin or varargout must appear last in the argument list, following anyrequired input or output variables.

That is, the function call must specify therequired arguments first. For example, these function declaration lines showthe correct placement of varargin and varargout.function [out1,out2] = example1(a,b,varargin)function [i,j,varargout] = example2(x1,y1,x2,y2,flag)17-18Local and Global VariablesLocal and Global VariablesThe same guidelines that apply to MATLAB variables at the command line alsoapply to variables in M-files:• You do not need to type or declare variables.

Before assigning one variable toanother, however, you must be sure that the variable on the right-hand sideof the assignment has a value.• Any operation that assigns a value to a variable creates the variable ifneeded, or overwrites its current value if it already exists.• MATLAB variable names consist of a letter followed by any number ofletters, digits, and underscores. MATLAB distinguishes between uppercaseand lowercase characters, so A and a are not the same variable.• MATLAB uses only the first 31 characters of variable names.Ordinarily, each MATLAB function, defined by an M-file, has its own localvariables, which are separate from those of other functions, and from those ofthe base workspace.

However, if several functions, and possibly the baseworkspace, all declare a particular name as global, then they all share a singlecopy of that variable. Any assignment to that variable, in any function, isavailable to all the other functions declaring it global.Suppose you want to study the effect of the interaction coefficients, α and β, inthe Lotka-Volterra predator-prey model.y· 1 = y 1 – αy 1 y 2y· = – y + βy y221 2Create an M-file, lotka.m.function yp = lotka(t,y)%LOTKALotka-Volterra predator-prey model.global ALPHA BETAyp = [y(1) – ALPHA*y(1)*y(2); –y(2) + BETA*y(1)*y(2)];Then interactively enter the statementsglobal ALPHA BETAALPHA = 0.01BETA = 0.0217-1917M-File Programming[t,y] = ode23('lotka',0,10,[1; 1]);plot(t,y)The two global statements make the values assigned to ALPHA and BETA at thecommand prompt available inside the function defined by lotka.m.

They canbe modified interactively and new solutions obtained without editing any files.For your MATLAB application to work with global variables:• Declare the variable as global in every function that requires access to it. Toenable the workspace to access the global variable, also declare it as globalfrom the command line.• In each function, issue the global command before the first occurrence of thevariable name. The top of the M-file is recommended.MATLAB global variable names are typically longer and more descriptive thanlocal variable names, and sometimes consist of all uppercase characters.

Характеристики

Тип файла
PDF-файл
Размер
6,57 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Зачем заказывать выполнение своего задания, если оно уже было выполнено много много раз? Его можно просто купить или даже скачать бесплатно на СтудИзбе. Найдите нужный учебный материал у нас!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6989
Авторов
на СтудИзбе
262
Средний доход
с одного платного файла
Обучение Подробнее
{user_main_secret_data}