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

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

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

If any of the examples in this section give unexpectedresults, clear the cell array from the workspace and try again.MATLAB displays the cell array A in a condensed form.A =[3x3 double][3.0000+ 7.0000i]'Anne Smith'[1x21 double]To display the full cell contents, use the celldisp function. For a high-levelgraphical display of cell architecture, use cellplot.If you assign data to a cell that is outside the dimensions of the current array,MATLAB automatically expands the array to include the subscripts youspecify.

It fills any intervening cells with empty matrices. For example, theassignment below turns the 2-by-2 cell array A into a 3-by-3 cell array.20-2120Structures and Cell ArraysA(3,3) = {5};cell 1,1107452cell 2,13+7icell 1,2389cell 1,3[ ]'Anne Smith'cell 2,2cell 2,3[ ][–3.14...3.14]cell 3,1cell 3,2[ ][ ]cell 3,35Cell Array Syntax: Using BracesThe curly braces, “{}”, are cell array constructors, just as square brackets arenumeric array constructors. Curly braces behave similarly to square brackets,except that you can nest curly braces to denote nesting of cells (see “NestingCell Arrays” for details).Curly braces use commas or spaces to indicate column breaks and semicolonsto indicate row breaks between cells.

For example,C = {[1 2], [3 4]; [5 6], [7 8]};results incell 1,1 cell 1,2[1 2][3 4]cell 2,1 cell 2,2[5 6][7 8]Use square brackets to concatenate cell arrays, just as you do for numericarrays.20-22Cell ArraysPreallocating Cell Arrays with the cell FunctionThe cell function allows you to preallocate empty cell arrays of the specifiedsize. For example, this statement creates an empty 2-by-3 cell array.B = cell(2,3);Use assignment statements to fill the cells of B.B(1,3) = {1:3};Obtaining Data from Cell ArraysYou can obtain data from cell arrays and store the result as either a standardarray or a new cell array.

This section discusses:• Accessing cell contents using content indexing• Accessing a subset of cells using cell indexingAccessing Cell Contents Using Content IndexingYou can use content indexing on the right side of an assignment to access someor all of the data in a single cell. Specify the variable to receive the cell contentson the left side of the assignment. Enclose the cell index expression on the rightside of the assignment in curly braces. This indicates that you are assigningcell contents, not the cells themselves.Consider the 2-by-2 cell array N.N{1,1}N{1,2}N{2,1}N{2,2}====[1 2; 4 5];'Name';2–4i;7;You can obtain the string in N{1,2} usingc = N{1,2}c =Name20-2320Structures and Cell ArraysNote In assignments, you can use content indexing to access only a singlecell, not a subset of cells.

For example, the statements A{1,:} = value and B= A{1,:} are both invalid. However, you can use a subset of cells any placeyou would normally use a comma-separated list of variables (for example, asfunction inputs or when building an array). See the “Replacing Lists ofVariables with Cell Arrays” section for details.To obtain subsets of a cell’s contents, concatenate indexing expressions. Forexample, to obtain element (2,2) of the array in cell N{1,1}, use:d = N{1,1}(2,2)d =5Accessing a Subset of Cells Using Cell IndexingUse cell indexing to assign any set of cells to another variable, creating a newcell array. Use the colon operator to access subsets of cells within a cell array.cell 1,1 cell 1,2 cell 1,3359cell 1,1 cell 1,26cell 2,1 cell 2,2 cell 2,3560cell 3,1 cell 3,2 cell 3,347B = A(2:3,2:3)0cell 2,1 cell 2,2722Deleting CellsYou can delete an entire dimension of cells using a single statement.

Likestandard array deletion, use vector subscripting when deleting a row or columnof cells and assign the empty matrix to the dimension.A(cell_subscripts) = []20-24Cell ArraysWhen deleting cells, curly braces do not appear in the assignment statement atall.Reshaping Cell ArraysLike other arrays, you can reshape cell arrays using the reshape function. Thenumber of cells must remain the same after reshaping; you cannot use reshapeto add or remove cells.A = cell(3,4);size(A)ans =34B = reshape(A,6,2);size(B)ans =62Replacing Lists of Variables with Cell ArraysCell arrays can replace comma-separated lists of MATLAB variables in:• Function input lists• Function output lists• Display operations• Array constructions (square brackets and curly braces)If you use the colon to index multiple cells in conjunction with the curly bracenotation, MATLAB treats the contents of each cell as a separate variable.

Forexample, assume you have a cell array T where each cell contains a separatevector. The expression T{1:5} is equivalent to a comma-separated list of thevectors in the first five cells of T.Consider the cell array C.C(1) = {[1 2 3]};C(2) = {[1 0 1]};C(3) = {1:10};20-2520Structures and Cell ArraysC(4) = {[9 8 7]};C(5) = {3};To convolve the vectors in C(1) and C(2) using conv,d = conv(C{1:2})d =12423Display vectors two, three, and four withC{2:4}ans =1012387ans =145678910ans =9Similarly, you can create a new numeric array using the statementB = [C{1}; C{2}; C{4}]B =119208317You can also use content indexing on the left side of an assignment to create anew cell array where each cell represents a separate output argument.[D{1:2}] = eig(B)20-26Cell ArraysD =[3x3 double][3x3 double]You can display the actual eigenvalues and eigenvectors using D{1} and D{2}.Note The varargin and varargout arguments allow you to specify variablenumbers of input and output arguments for MATLAB functions that youcreate.

Both varargin and varargout are cell arrays, allowing them to holdvarious sizes and kinds of MATLAB data. See “Passing Variable Numbers ofArguments” on page 17-16 for details.Applying Functions and OperatorsUse indexing to apply functions and operators to the contents of cells. Forexample, use content indexing to call a function with the contents of a singlecell as an argument.A{1,1} = [1 2; 3 4];A{1,2} = randn(3,3);A{1,3} = 1:5;B = sum(A{1,1})B =46To apply a function to several cells of a non-nested cell array, use a loop.for k = 1:length(A)M{k} = sum(A{1,k});endOrganizing Data in Cell ArraysCell arrays are useful for organizing data that consists of different sizes orkinds of data. Cell arrays are better than structures for applications where:• You need to access multiple fields of data with one statement.20-2720Structures and Cell Arrays• You want to access subsets of the data as comma-separated variable lists.• You don’t have a fixed set of field names.• You routinely remove fields from the structure.As an example of accessing multiple fields with one statement, assume thatyour data consists of:• A 3-by-4 array consisting of measurements taken for an experiment.• A 15-character string containing a technician’s name.• A 3-by-4-by-5 array containing a record of measurements taken for the pastfive experiments.For many applications, the best data construct for this data is a structure.However, if you routinely access only the first two fields of information, then acell array might be more convenient for indexing purposes.This example shows how to access the first and second elements of the cellarray TEST.[newdata,name] = deal(TEST{1:2})This example shows how to access the first and second elements of thestructure TEST.newdata = TEST.measurename = TEST.nameThe varargin and varargout arguments are examples of the utility of cellarrays as substitutes for comma-separated lists.

Create a 3-by-3 numericarray A.A = [0 1 2;4 0 7;3 1 2];Now apply the normest (2-norm estimate) function to A, and assign the functionoutput to individual cells of B.[B{1:2}] = normest(A)B =[8.8826]20-28[4]Cell ArraysAll of the output values from the function are stored in separate cells of B. B(1)contains the norm estimate; B(2) contains the iteration count.Nesting Cell ArraysA cell can contain another cell array, or even an array of cell arrays. (Cells thatcontain noncell data are called leaf cells.) You can use nested curly braces, thecell function, or direct assignment statements to create nested cell arrays.You can then access and manipulate individual cells, subarrays of cells, or cellelements.Building Nested Arrays with Nested Curly BracesYou can nest pairs of curly braces to create a nested cell array.

For example,clear AA(1,1) = {magic(5)};A(1,2) = {{[5 2 8; 7 3 0; 6 7 3] 'Test 1'; [2–4i 5+7i] {17 []}}}A =[5x5 double]{2x2 cell}Note that the right side of the assignment is enclosed in two sets of curlybraces. The first set represents cell (1,2) of cell array A. The second “packages”the 2-by-2 cell array inside the outer cell.Building Nested Arrays with the cell FunctionTo nest cell arrays with the cell function, assign the output of cell to anexisting cell:1 Create an empty 1-by-2 cell array.A = cell(1,2);2 Create a 2-by-2 cell array inside A(1,2).A(1,2) = {cell(2,2)};3 Fill A, including the nested array, using assignments.A(1,1) = {magic(5)};A{1,2}(1,1) = {[5 2 8; 7 3 0; 6 7 3]};20-2920Structures and Cell ArraysA{1,2}(1,2) = {'Test 1'};A{1,2}(2,1) = {[2–4i 5+7i]};A{1,2}(2,2) = {cell(1,2)}A{1,2}{2,2}(1) = {17};Note the use of curly braces until the final level of nested subscripts.

This isrequired because you need to access cell contents to access cells within cells.You can also build nested cell arrays with direct assignments using thestatements shown in step 3 above.Indexing Nested Cell ArraysTo index nested cells, concatenate indexing expressions.

The first set ofsubscripts accesses the top layer of cells, and subsequent sets of parenthesesaccess successively deeper layers.For example, array A has three levels of nesting:cell 1,117 24 1 8 1523 5 7 14 164 6 13 20 2210 12 19 21 311 18 25 2 9cell 1,2576237803[2–4i 5+7i]'Test 1'17• To access the 5-by-5 array in cell (1,1), use A{1,1}.• To access the 3-by-3 array in position (1,1) of cell (1,2), use A{1,2}{1,1}.• To access the 2-by-2 cell array in cell (1,2), use A{1,2}.• To access the empty cell in position (2,2) of cell (1,2), useA{1,2}{2,2}{1,2}.Converting Between Cell and Numeric ArraysUse for loops to convert between cell and numeric formats. For example, createa cell array F.F{1,1} = [1 2; 3 4];F{1,2} = [–1 0; 0 1];20-30Cell ArraysF{2,1} = [7 8; 4 1];F{2,2} = [4i 3+2i; 1–8i 5];Now use three for loops to copy the contents of F into a numeric array NUM.for k = 1:4for m = 1:2for n = 1:2NUM(m,n,k) = F{k}(m,n);endendendSimilarly, you must use for loops to assign each value of a numeric array to asingle cell of a cell array.G = cell(1,16);for m = 1:16G{m} = NUM(m);endCell Arrays of StructuresUse cell arrays to store groups of structures with different field architectures.c_str = cell(1,2);c_str{1}.label = '12/2/94 – 12/5/94';c_str{1}.obs = [47 52 55 48; 17 22 35 11];c_str{2}.xdata = [–0.03 0.41 1.98 2.12 17.11];c_str{2}.ydata = [–3 5 18 0 9];c_str{2}.zdata = [0.6 0.8 1 2.2 3.4];cell 2cell 1c_str(1).label.testc_str(2)'12/2/94 – 12/5/94'47 52 55 4817 22 35 11.name[–0.03 0.41 1.98 2.12 17.11].billing[–3 5 18 0 9].test[0.6 0.8 1 2.2 3.4]Cell 1 of the c_str array contains a structure with two fields, one a string andthe other a vector.

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

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

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

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