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

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

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

mind contains the integers from 1 throughthe row size of A. The nind variable contains the integers from 1 through thecolumn size of A.Step 3 uses a MATLAB vectorization trick to replicate a single column of datathrough any number of columns. The code isB = A(:,ones(1,n_cols))where n_cols is the desired number of columns in the resulting matrix.Step 4 uses array indexing to create the output array. Each element of the rowindex array, mind, is paired with each element of the column index array, nind,using the following procedure:1 The first element of mind, the row index, is paired with each element of nind.MATLAB moves through the nind matrix in a columnwise fashion, somind(1,1) goes with nind(1,1), then nind(2,1), and so on.

The result fillsthe first row of the output array.2 Moving columnwise through mind, each element is paired with the elementsof nind as above. Each complete pass through the nind matrix fills one rowof the output array.Preallocating ArraysYou can often improve code execution time by preallocating the arrays thatstore output results. Preallocation prevents MATLAB from having to resize anarray each time you enlarge it. Use the appropriate preallocation function forthe kind of array you are working with.Array TypeFunctionExamplesNumericarrayzerosy = zeros(1,100);Cell arraycellB = cell(2,3);B{1,3} = 1:3;B{2,2} = 'string';17-7317M-File ProgrammingArray TypeFunctionExamplesStructurearraystruct,repmatdata = repmat(struct('x',[1 3],...'y',[5 6]), 1, 3);Preallocation also helps reduce memory fragmentation if you work with largematrices.

In the course of a MATLAB session, memory can become fragmenteddue to dynamic memory allocation and deallocation. This can result in plentyof free memory, but not enough contiguous space to hold a large variable.Preallocation helps prevent this by allowing MATLAB to “grab” sufficientspace for large data constructs at the beginning of a computation.Making Efficient Use of MemoryThis section discusses the following ways to conserve memory and improvememory use:• “Memory Management Functions”• “Removing a Function From Memory”• “Nested Function Calls”• “Variables and Memory”• “PC-Specific Topics”• “UNIX-Specific Topics”• “What Does “Out of Memory” Mean?”Memory Management FunctionsMATLAB has five functions to improve how memory is handled:• clear removes variables from memory.• pack saves existing variables to disk, then reloads them contiguously.Because of time considerations, you should not use pack within loops orM-file functions.• quit exits MATLAB and returns all allocated memory to the system.• save selectively stores variables to disk.• load reloads a data file saved with the save command.17-74Optimizing MATLAB CodeNote save and load are faster than MATLAB low-level file I/O routines.

saveand load have been optimized to run faster and reduce memoryfragmentation.On some systems, the whos function displays the amount of free memoryremaining. However, be aware that:• If you delete a variable from the workspace, the amount of free memoryindicated by whos usually does not get larger unless the deleted variableoccupied the highest memory addresses. The number actually indicates theamount of contiguous, unused memory. Clearing the highest variable makesthe number larger, but clearing a variable beneath the highest variable hasno effect. This means that you might have more free memory than isindicated by whos.• Computers with virtual memory do not display the amount of free memoryremaining because neither MATLAB nor the hardware imposes limitations.Removing a Function From MemoryMATLAB creates a list of M- and MEX-filenames at startup for all files thatreside below the matlab/toolbox directories.

This list is stored in memory andis freed only when a new list is created during a call to the path function.Function M-file code and MEX-file relocatable code are loaded into memorywhen the corresponding function is called. The M-file code or relocatable codeis removed from memory when:• The function is called again and a new version now exists.• The function is explicitly cleared with the clear command.• All functions are explicitly cleared with the clear functions command.• MATLAB runs out of memory.Nested Function CallsThe amount of memory used by nested functions is the same as the amountused by calling them on consecutive lines.

These two examples require thesame amount of memory.17-7517M-File Programmingresult = function2(function1(input99));result = function1(input99);result = function2(result);Variables and MemoryMemory is allocated for variables whenever the left-hand side variable in anassignment does not exist.

The statementx = 10allocates memory, but the statementx(10) = 1does not allocate memory if the 10th element of x exists.To conserve memory:• Avoid creating large temporary variables, and clear temporary variableswhen they are no longer needed.• When working with arrays of fixed size, pre-allocate them rather thanhaving MATLAB resize the array each time you enlarge it.• Set variables equal to the empty matrix [] to free memory, or clear themusingclear variable_name• Reuse variables as much as possible.Global Variables.

Declaring variables as global merely puts a flag in a symboltable. It does not use any more memory than defining nonglobal variables.Consider the following example.global aa = 5;Now there is one copy of a stored in the MATLAB workspace. Typingclear aremoves a from the MATLAB workspace, but it still exists in the globalworkspace.17-76Optimizing MATLAB Codeclear global aremoves a from the global workspace.PC-Specific Topics• There are no functions implemented to manipulate the way MATLABhandles Microsoft Windows system resources. Windows uses systemresources to track fonts, windows, and screen objects.

Resources can bedepleted by using multiple figure windows, multiple fonts, or severalUicontrols. The best way to free up system resources is to close all inactivewindows. Iconified windows still use resources.• The performance of a permanent swap file is typically better than atemporary swap file.• Typically a swap file twice the size of the installed RAM is sufficient.UNIX-Specific Topics• Memory that MATLAB requests from the operating system is not returnedto the operating system until the MATLAB process in finished.• MATLAB requests memory from the operating system when there is notenough memory available in the MATLAB heap to store the currentvariables.

It reuses memory in the heap as long as the size of the memorysegment required is available in the MATLAB heap.For example, on one machine these statements use approximately 15.4 MBof RAM.a = rand(1e6,1);b = rand(1e6,1);These statements use approximately 16.4 MB of RAM.c = rand(2.1e6,1);These statements use approximately 32.4 MB of RAM.a = rand(1e6,1);b = rand(1e6,1);clear17-7717M-File Programmingc = rand(2.1e6,1);This is because MATLAB is not able to fit a 2.1 MB array in the spacepreviously occupied by two 1 MB arrays. The simplest way to preventoverallocation of memory, is to preallocate the largest vector.

This series ofstatements uses approximately 32.4 MB of RAMa = rand(1e6,1);b = rand(1e6,1);clearc = rand(2.1e6,1);while these statements use only about 16.4 MB of RAMc = rand(2.1e6,1);cleara = rand(1e6,1);b = rand(1e6,1);Allocating the largest vectors first allows for optimal use of the availablememory.What Does “Out of Memory” Mean?Typically the Out of Memory message appears because MATLAB asked theoperating system for a segment of memory larger than what is currentlyavailable. Use any of the techniques discussed in this section to help optimizethe available memory. If the Out of Memory message still appears:• Increase the size of the swap file.• Make sure that there are no external constraints on the memory accessibleto MATLAB (on UNIX systems use the limit command to check).• Add more memory to the system.• Reduce the size of your data.17-7818Character Arrays (Strings)Character Arrays .

. . . . . . . . . .Creating Character Arrays . . . . . . . .Creating Two-Dimensional Character ArraysConverting Characters to Numeric Values .......................... 18-5. 18-5. 18-6. 18-7Cell Arrays of Strings . . . . . . . . . . . . . . . . 18-8Converting to a Cell Array of Strings . . . . . . . . . . 18-8String Comparisons .

. . . . . .Comparing Strings For Equality . . .Comparing for Equality Using OperatorsCategorizing Characters Within a String................................18-1018-1018-1118-12Searching and Replacing . . . . . . . . . . . . . 18-13String/Numeric Conversion . . .

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

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

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

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