Главная » Просмотр файлов » Matlab - Getting start

Matlab - Getting start (779439), страница 11

Файл №779439 Matlab - Getting start (Matlab - Getting start) 11 страницаMatlab - Getting start (779439) страница 112017-12-27СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

A cell array of empty matrices can be created with thecell function. But, more often, cell arrays are created by enclosing amiscellaneous collection of things in curly braces, {}. The curly braces are alsoused with subscripts to access the contents of various cells. For example,C = {A sum(A) prod(prod(A))}produces a 1-by-3 cell array. The three cells contain the magic square, the rowvector of column sums, and the product of all its elements. When C is displayed,you seeC =[4x4 double][1x4 double][20922789888000]This is because the first two cells are too large to print in this limited space, butthe third cell contains only a single number, 16!, so there is room to print it.5-95Programming with MATLABHere are two important points to remember. First, to retrieve the contents ofone of the cells, use subscripts in curly braces.

For example, C{1} retrieves themagic square and C{3} is 16!. Second, cell arrays contain copies of other arrays,not pointers to those arrays. If you subsequently change A, nothing happens toC.Three-dimensional arrays can be used to store a sequence of matrices of thesame size. Cell arrays can be used to store a sequence of matrices of differentsizes. For example,M = cell(8,1);for n = 1:8M{n} = magic(n);endMproduces a sequence of magic squares of different order.M =[[[[[[[[5-102x23x34x45x56x67x78x81]double]double]double]double]double]double]double]Other Data Structures236160675795554121351501617474620214342244026273736303133323435292838392541232244451918484915145253111056858595462631...641623135111089761241415181635743921421You can retrieve our old friend withM{4}Characters and TextEnter text into MATLAB using single quotes.

For example,s = 'Hello'The result is not the same kind of numeric matrix or array we have beendealing with up to now. It is a 1-by-5 character array.5-115Programming with MATLABInternally, the characters are stored as numbers, but not in floating-pointformat. The statementa = double(s)converts the character array to a numeric matrix containing floating-pointrepresentations of the ASCII codes for each character.

The result isa =72101108108111The statements = char(a)reverses the conversion.Converting numbers to characters makes it possible to investigate the variousfonts available on your computer. The printable characters in the basic ASCIIcharacter set are represented by the integers 32:127.

(The integers less than32 represent nonprintable control characters.) These integers are arranged inan appropriate 6-by-16 array withF = reshape(32:127,16,6)';The printable characters in the extended ASCII character set are representedby F+128.

When these integers are interpreted as characters, the resultdepends on the font currently being used. Type the statementschar(F)char(F+128)and then vary the font being used for the MATLAB Command Window. SelectPreferences from the File menu. Be sure to try the Symbol and Wingdingsfonts, if you have them on your computer. Here is one example of the kind ofoutput you might obtain.!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_‘abcdefghijklmnopqrstuvwxyz{|}~†°¢£§•¶ß®©™´¨¦ÆØ5-12Other Data Structures×±ðŠ¥µ¹²³¼½ªº¾æø¿¡¬ÐƒÝý«»…þÀÃÕŒœ-—“”‘’÷ÞÿŸ⁄¤‹›??‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔšÒÚÛÙ ˆ˜¯ °¸″ ÿConcatenation with square brackets joins text variables together into largerstrings.

The statementh = [s, ' world']joins the strings horizontally and producesh =Hello worldThe statementv = [s; 'world']joins the strings vertically and producesv =HelloworldNote that a blank has to be inserted before the 'w' in h and that both words inv have to have the same length. The resulting arrays are both character arrays;h is 1-by-11 and v is 2-by-5.To manipulate a body of text containing lines of different lengths, you have twochoices – a padded character array or a cell array of strings. The char functionaccepts any number of lines, adds blanks to each line to make them all thesame length, and forms a character array with each line in a separate row.

Forexample,S = char('A','rolling','stone','gathers','momentum.')produces a 5-by-9 character array.S =Arollingstonegathersmomentum.5-135Programming with MATLABThere are enough blanks in each of the first four rows of S to make all the rowsthe same length. Alternatively, you can store the text in a cell array. Forexample,C = {'A';'rolling';'stone';'gathers';'momentum.'}is a 5-by-1 cell array.C ='A''rolling''stone''gathers''momentum.'You can convert a padded character array to a cell array of strings withC = cellstr(S)and reverse the process withS = char(C)StructuresStructures are multidimensional MATLAB arrays with elements accessed bytextual field designators.

For example,S.name = 'Ed Plum';S.score = 83;S.grade = 'B+'creates a scalar structure with three fields.S =name: 'Ed Plum'score: 83grade: 'B+'Like everything else in MATLAB, structures are arrays, so you can insertadditional elements. In this case, each element of the array is a structure withseveral fields. The fields can be added one at a time,5-14Other Data StructuresS(2).name = 'Toni Miller';S(2).score = 91;S(2).grade = 'A-';or, an entire element can be added with a single statement.S(3) = struct('name','Jerry Garcia',...'score',70,'grade','C')Now the structure is large enough that only a summary is printed.S =1x3 struct array with fields:namescoregradeThere are several ways to reassemble the various fields into other MATLABarrays.

They are all based on the notation of a comma separated list. If you typeS.scoreit is the same as typingS(1).score, S(2).score, S(3).scoreThis is a comma separated list. Without any other punctuation, it is not veryuseful. It assigns the three scores, one at a time, to the default variable ans anddutifully prints out the result of each assignment. But when you enclose theexpression in square brackets,[S.score]it is the same as[S(1).score, S(2).score, S(3).score]which produces a numeric row vector containing all of the scores.ans =839170Similarly, typingS.name5-155Programming with MATLABjust assigns the names, one at time, to ans. But enclosing the expression incurly braces,{S.name}creates a 1-by-3 cell array containing the three names.ans ='Ed Plum''Toni Miller''Jerry Garcia'Andchar(S.name)calls the char function with three arguments to create a character array fromthe name fields,ans =Ed PlumToni MillerJerry Garcia5-16Scripts and FunctionsScripts and FunctionsMATLAB is a powerful programming language as well as an interactivecomputational environment.

Files that contain code in the MATLAB languageare called M-files. You create M-files using a text editor, then use them as youwould any other MATLAB function or command.There are two kinds of M-files:• Scripts, which do not accept input arguments or return output arguments.They operate on data in the workspace.• Functions, which can accept input arguments and return output arguments.Internal variables are local to the function.If you’re a new MATLAB programmer, just create the M-files that you want totry out in the current directory. As you develop more of your own M-files, youwill want to organize them into other directories and personal toolboxes thatyou can add to MATLAB’s search path.If you duplicate function names, MATLAB executes the one that occurs first inthe search path.To view the contents of an M-file, for example, myfunction.m, usetype myfunctionScriptsWhen you invoke a script, MATLAB simply executes the commands found inthe file.

Scripts can operate on existing data in the workspace, or they cancreate new data on which to operate. Although scripts do not return outputarguments, any variables that they create remain in the workspace, to be usedin subsequent computations. In addition, scripts can produce graphical outputusing functions like plot.For example, create a file called magicrank.m that contains these MATLABcommands.% Investigate the rank of magic squaresr = zeros(1,32);for n = 3:32r(n) = rank(magic(n));end5-175Programming with MATLABrbar(r)Typing the statementmagicrankcauses MATLAB to execute the commands, compute the rank of the first 30magic squares, and plot a bar graph of the result. After execution of the file iscomplete, the variables n and r remain in the workspace.3530252015105005101520253035FunctionsFunctions are M-files that can accept input arguments and return outputarguments. The name of the M-file and of the function should be the same.Functions operate on variables within their own workspace, separate from theworkspace you access at the MATLAB command prompt.A good example is provided by rank.

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

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

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

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