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

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

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

. . . . . . . . . 18-15Array/String Conversion . . . . . . . . . . . . . . . 18-1618Character Arrays (Strings)This chapter explains MATLAB’s support for string data. It describes the twoways that MATLAB represents strings:• “Character Arrays”• “Cell Arrays of Strings”It also describes the operations that you can perform on string data under thefollowing topics:• “String Comparisons”• “Searching and Replacing”• “String/Numeric Conversion”This table shows the string functions, which are located in the directory namedstrfun in the MATLAB Toolbox.CategoryFunctionDescriptionGeneralblanksString of blankscellstrCreate cell array of strings from character arraycharCreate character array (string)deblankRemove trailing blanksevalExecute string with MATLAB expressioniscellstrTrue for cell array of stringsischarTrue for character arrayisletterTrue for letters of alphabet.isspaceTrue for whitespace characters.String Tests18-2CategoryFunctionDescriptionStringOperationsfindstrFind one string within anotherlowerConvert string to lowercasestrcatConcatenate stringsstrcmpCompare stringsstrcmpiCompare strings, ignoring casestrjustJustify stringstrmatchFind matches for stringstrncmpCompare first N characters of stringsstrncmpiCompare first N characters, ignoring casestrrepReplace string with anotherstrtokFind token in stringstrvcatConcatenate strings verticallyupperConvert string to uppercasedoubleConvert string to numeric codesint2strConvert integer to stringmat2strConvert matrix to eval’able stringnum2strConvert number to stringsprintfWrite formatted data to stringstr2doubleConvert string to double-precision valuestr2numConvert string to numbersscanfRead string under format controlString to NumberConversion18-31818-4Character Arrays (Strings)CategoryFunctionDescriptionBase NumberConversionbase2decConvert base B string to decimal integerbin2decConvert binary string to decimal integerdec2baseConvert decimal integer to base B stringdec2binConvert decimal integer to binary stringdec2hexConvert decimal integer to hexadecimal stringhex2decConvert hexadecimal string to decimal integerhex2numConvert IEEE hexadecimal to double-precisionnumberCharacter ArraysCharacter ArraysIn MATLAB, the term string refers to an array of characters.

MATLABrepresents each character internally as its corresponding numeric value.Unless you want to access these values, however, you can simply work with thecharacters as they display on screen.This section covers:• “Creating Character Arrays”• “Creating Two-Dimensional Character Arrays”• “Converting Characters to Numeric Values”Creating Character ArraysSpecify character data by placing characters inside a pair of single quotes.

Forexample, this line creates a 1-by-13 character array called name.name = 'Thomas R. Lee';In the workspace, the output of whos showsNameSizeBytesname1x1326Classchar arrayYou can see that a character uses two bytes of storage internally.The class and ischar functions show name’s identity as a character array.class(name)ans =charischar(name)ans =118-518Character Arrays (Strings)You can also join two or more character arrays together to create a newcharacter array. Use either the string concatenation function, strcat, or theMATLAB concatenation operator, [], to do this.

The latter preserves anytrailing spaces found in the input arrays.name = 'Thomas R. Lee';title = ' Sr. Developer';strcat(name,',',title)ans =Thomas R. Lee, Sr. DeveloperYou can also concatenate strings vertically with strvcat.Creating Two-Dimensional Character ArraysWhen creating a two-dimensional character array, be sure that each row hasthe same length.

For example, this line is legal because both input rows haveexactly 13 characters.name = ['Thomas R. Lee' ; 'Sr. Developer']name =Thomas R. LeeSr. DeveloperWhen creating character arrays from strings of different lengths, you can padthe shorter strings with blanks to force rows of equal length.name = ['Thomas R. Lee'; 'Senior Developer'];A simpler way to create string arrays is to use the char function. charautomatically pads all strings to the length of the longest input string. In thisexample, char pads the 13-character input string 'Thomas R.

Lee' with threetrailing blanks so that it will be as long as the second string.name = char('Thomas R. Lee','Senior Developer')name =Thomas R. Lee18-6Character ArraysSenior DeveloperWhen extracting strings from an array, use the deblank function to remove anytrailing blanks.trimname = deblank(name(1,:))trimname =Thomas R. Leesize(trimname)ans =113Converting Characters to Numeric ValuesCharacter arrays store each character as a 16-bit numeric value. Use thedouble function to convert strings to their numeric values, and char to revertto character representation.name = double(name)name =84104111109971153282463276101101name = char(name)name =Thomas R.

LeeUse str2num to convert a character array to the numeric value represented bythat string.str = '37.294e-1';val = str2num(str)val =3.729418-718Character Arrays (Strings)Cell Arrays of StringsIt’s often convenient to store groups of strings in cell arrays instead of standardcharacter arrays. This prevents you from having to pad strings with blanks tocreate character arrays with rows of equal length.

A set of functions enablesyou to work with cell arrays of strings:• You can convert between standard character arrays and cell arrays ofstrings.• You can apply string comparison operations to cell arrays of strings.For details on cell arrays see the “Structures and Cell Arrays” chapter.Converting to a Cell Array of StringsThe cellstr function converts a character array into a cell array of strings.Consider the character arraydata = ['Allison Jones';'Development';'Phoenix'];Each row of the matrix is padded so that all have equal length (in this case, 13characters).Now use cellstr to create a column vector of cells, each cell containing one ofthe strings from the data array.celldata = cellstr(data)celldata ='Allison Jones''Development''Phoenix'Note that the cellstr function strips off the blanks that pad the rows of theinput string matrix.length(celldata{3})ans =718-8Cell Arrays of StringsThe iscellstr function determines if the input argument is a cell array ofstrings.

It returns a logical true (1) in the case of celldata.iscellstr(celldata)ans =1Use char to convert back to a standard padded character array.strings = char(celldata)strings =Allison JonesDevelopmentPhoenixString/Numeric ConversionThe str2double function converts a cell array of strings to the double-precisionvalues represented by the strings.c = {'37.294e-1'; '-58.375'; '13.796'};str2double(c)ans =3.7294-58.375013.796018-918Character Arrays (Strings)String ComparisonsThere are several ways to compare strings and substrings:• You can compare two strings, or parts of two strings, for equality.• You can compare individual characters in two strings for equality.• You can categorize every element within a string, determining whether eachelement is a character or whitespace.These functions work for both character arrays and cell arrays of strings.Comparing Strings For EqualityThere are four functions that determine if two input strings are identical:• strcmp determines if two strings are identical.• strncmp determines if the first n characters of two strings are identical.• strcmpi and strncmpi are the same as strcmp and strncmp, except that theyignore case.Consider the two stringsstr1 = 'hello';str2 = 'help';Strings str1 and str2 are not identical, so invoking strcmp returns 0 (false).For example,C = strcmp(str1,str2)C =0Note For C programmers, this is an important difference between MATLAB’sstrcmp and C’s strcmp(), which returns 0 if the two strings are the same.18-10String ComparisonsThe first three characters of str1 and str2 are identical, so invoking strncmpwith any value up to 3 returns 1.C = strncmp(str1,str2,2)C =1These functions work cell-by-cell on a cell array of strings.

Consider the two cellarrays of stringsA = {'pizza';'chips';'candy'};B = {'pizza';'chocolate';'pretzels'};Now apply the string comparison functions.strcmp(A,B)ans =100strncmp(A,B,1)ans =110Comparing for Equality Using OperatorsYou can use MATLAB relational operators on character arrays, as long as thearrays you are comparing have equal dimensions, or one is a scalar. Forexample, you can use the equality operator (==) to determine which charactersin two strings match.18-1118Character Arrays (Strings)A = 'fate';B = 'cake';A == Bans =0101All of the relational operators (>, >=, <, <=, ==, !=) compare the values ofcorresponding characters.Categorizing Characters Within a StringThere are two functions for categorizing characters inside a string:• isletter determines if a character is a letter• isspace determines if a character is whitespace (blank, tab, or new line)For example, create a string named mystring.mystring = 'Room 401';isletter examines each character in the string, producing an output vector ofthe same length as mystring.A = isletter(mystring)A =11110000The first four elements in A are 1 (true) because the first four characters ofmystring are letters.18-12Searching and ReplacingSearching and ReplacingMATLAB provides several functions for searching and replacing characters ina string.

Consider a string named label.label = 'Sample 1, 10/28/95';The strrep function performs the standard search-and-replace operation. Usestrrep to change the date from '10/28' to '10/30'.newlabel = strrep(label,'28','30')newlabel =Sample 1, 10/30/95findstr returns the starting position of a substring within a longer string. Tofind all occurrences of the string 'amp' inside labelposition = findstr('amp',label)position =2The position within label where the only occurrence of 'amp' begins is thesecond character.The strtok function returns the characters before the first occurrence of adelimiting character in an input string.

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

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

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

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