MATLAB – Strings

MATLAB – Strings ”; Previous Next Creating a character string is quite simple in MATLAB. In fact, we have used it many times. For example, you type the following in the command prompt − Live Demo my_string = ”Tutorials Point” MATLAB will execute the above statement and return the following result − my_string = Tutorials Point MATLAB considers all variables as arrays, and strings are considered as character arrays. Let us use the whos command to check the variable created above − whos MATLAB will execute the above statement and return the following result − Name Size Bytes Class Attributes my_string 1×16 32 char Interestingly, you can use numeric conversion functions like uint8 or uint16 to convert the characters in the string to their numeric codes. The char function converts the integer vector back to characters − Example Create a script file and type the following code into it − Live Demo my_string = ”Tutorial””s Point”; str_ascii = uint8(my_string) % 8-bit ascii values str_back_to_char= char(str_ascii) str_16bit = uint16(my_string) % 16-bit ascii values str_back_to_char = char(str_16bit) When you run the file, it displays the following result − str_ascii = 84 117 116 111 114 105 97 108 39 115 32 80 111 105 110 116 str_back_to_char = Tutorial”s Point str_16bit = 84 117 116 111 114 105 97 108 39 115 32 80 111 105 110 116 str_back_to_char = Tutorial”s Point Rectangular Character Array The strings we have discussed so far are one-dimensional character arrays; however, we need to store more than that. We need to store more dimensional textual data in our program. This is achieved by creating rectangular character arrays. Simplest way of creating a rectangular character array is by concatenating two or more one-dimensional character arrays, either vertically or horizontally as required. You can combine strings vertically in either of the following ways − Using the MATLAB concatenation operator [] and separating each row with a semicolon (;). Please note that in this method each row must contain the same number of characters. For strings with different lengths, you should pad with space characters as needed. Using the char function. If the strings are of different lengths, char pads the shorter strings with trailing blanks so that each row has the same number of characters. Example Create a script file and type the following code into it − Live Demo doc_profile = [”Zara Ali ”; … ”Sr. Surgeon ”; … ”R N Tagore Cardiology Research Center”] doc_profile = char(”Zara Ali”, ”Sr. Surgeon”, … ”RN Tagore Cardiology Research Center”) When you run the file, it displays the following result − doc_profile = Zara Ali Sr. Surgeon R N Tagore Cardiology Research Center doc_profile = Zara Ali Sr. Surgeon RN Tagore Cardiology Research Center You can combine strings horizontally in either of the following ways − Using the MATLAB concatenation operator, [] and separating the input strings with a comma or a space. This method preserves any trailing spaces in the input arrays. Using the string concatenation function, strcat. This method removes trailing spaces in the inputs. Example Create a script file and type the following code into it − Live Demo name = ”Zara Ali ”; position = ”Sr. Surgeon ”; worksAt = ”R N Tagore Cardiology Research Center”; profile = [name ”, ” position ”, ” worksAt] profile = strcat(name, ”, ”, position, ”, ”, worksAt) When you run the file, it displays the following result − profile = Zara Ali , Sr. Surgeon , R N Tagore Cardiology Research Center profile = Zara Ali,Sr. Surgeon,R N Tagore Cardiology Research Center Combining Strings into a Cell Array From our previous discussion, it is clear that combining strings with different lengths could be a pain as all strings in the array has to be of the same length. We have used blank spaces at the end of strings to equalize their length. However, a more efficient way to combine the strings is to convert the resulting array into a cell array. MATLAB cell array can hold different sizes and types of data in an array. Cell arrays provide a more flexible way to store strings of varying length. The cellstr function converts a character array into a cell array of strings. Example Create a script file and type the following code into it − Live Demo name = ”Zara Ali ”; position = ”Sr. Surgeon ”; worksAt = ”R N Tagore Cardiology Research Center”; profile = char(name, position, worksAt); profile = cellstr(profile); disp(profile) When you run the file, it displays the following result − { [1,1] = Zara Ali [2,1] = Sr. Surgeon [3,1] = R N Tagore Cardiology Research Center } String Functions in MATLAB MATLAB provides numerous string functions creating, combining, parsing, comparing and manipulating strings. Following table provides brief description of the string functions in MATLAB − Function Purpose Functions for storing text in character arrays, combine character arrays, etc. blanks Create string of blank characters cellstr Create cell array of strings from character array char Convert to character array (string) iscellstr Determine whether input is cell array of strings ischar Determine whether item is character array sprintf Format data into string strcat Concatenate strings horizontally strjoin Join strings in cell array into single string Functions for identifying parts of strings, find and replace substrings ischar Determine whether item is character array isletter Array elements that are alphabetic letters isspace Array elements that are space characters isstrprop Determine whether string is of specified category sscanf Read formatted data from string strfind Find one string within another strrep Find and replace substring strsplit Split string at specified delimiter strtok Selected parts of string validatestring Check validity of text string symvar Determine symbolic variables in expression regexp Match regular expression (case sensitive) regexpi Match regular expression (case insensitive) regexprep Replace string using regular expression regexptranslate Translate string into regular expression Functions for string comparison strcmp Compare strings (case sensitive) strcmpi Compare strings (case insensitive) strncmp Compare first n characters of strings (case sensitive) strncmpi

MATLAB – Syntax

MATLAB – Basic Syntax ”; Previous Next MATLAB environment behaves like a super-complex calculator. You can enter commands at the >> command prompt. MATLAB is an interpreted environment. In other words, you give a command and MATLAB executes it right away. Hands on Practice Type a valid expression, for example, Live Demo 5 + 5 And press ENTER When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is − ans = 10 Let us take up few more examples − Live Demo 3 ^ 2 % 3 raised to the power of 2 When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is − ans = 9 Another example, Live Demo sin(pi /2) % sine of angle 90o When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is − ans = 1 Another example, Live Demo 7/0 % Divide by zero When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is − ans = Inf warning: division by zero Another example, Live Demo 732 * 20.3 When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is − ans = 1.4860e+04 MATLAB provides some special expressions for some mathematical symbols, like pi for π, Inf for ∞, i (and j) for √-1 etc. Nan stands for ”not a number”. Use of Semicolon (;) in MATLAB Semicolon (;) indicates end of statement. However, if you want to suppress and hide the MATLAB output for an expression, add a semicolon after the expression. For example, Live Demo x = 3; y = x + 5 When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is − y = 8 Adding Comments The percent symbol (%) is used for indicating a comment line. For example, x = 9 % assign the value 9 to x You can also write a block of comments using the block comment operators % { and % }. The MATLAB editor includes tools and context menu items to help you add, remove, or change the format of comments. Commonly used Operators and Special Characters MATLAB supports the following commonly used operators and special characters − Operator Purpose + Plus; addition operator. – Minus; subtraction operator. * Scalar and matrix multiplication operator. .* Array multiplication operator. ^ Scalar and matrix exponentiation operator. .^ Array exponentiation operator. Left-division operator. / Right-division operator. . Array left-division operator. ./ Array right-division operator. : Colon; generates regularly spaced elements and represents an entire row or column. ( ) Parentheses; encloses function arguments and array indices; overrides precedence. [ ] Brackets; enclosures array elements. . Decimal point. … Ellipsis; line-continuation operator , Comma; separates statements and elements in a row ; Semicolon; separates columns and suppresses display. % Percent sign; designates a comment and specifies formatting. _ Quote sign and transpose operator. ._ Nonconjugated transpose operator. = Assignment operator. Special Variables and Constants MATLAB supports the following special variables and constants − Name Meaning ans Most recent answer. eps Accuracy of floating-point precision. i,j The imaginary unit √-1. Inf Infinity. NaN Undefined numerical result (not a number). pi The number π Naming Variables Variable names consist of a letter followed by any number of letters, digits or underscore. MATLAB is case-sensitive. Variable names can be of any length, however, MATLAB uses only first N characters, where N is given by the function namelengthmax. Saving Your Work The save command is used for saving all the variables in the workspace, as a file with .mat extension, in the current directory. For example, save myfile You can reload the file anytime later using the load command. load myfile Print Page Previous Next Advertisements ”;

MATLAB – Environment Setup

MATLAB – Environment Setup ”; Previous Next Local Environment Setup Setting up MATLAB environment is a matter of few clicks. The installer can be downloaded from here. MathWorks provides the licensed product, a trial version and a student version as well. You need to log into the site and wait a little for their approval. After downloading the installer the software can be installed through few clicks. Understanding the MATLAB Environment MATLAB development IDE can be launched from the icon created on the desktop. The main working window in MATLAB is called the desktop. When MATLAB is started, the desktop appears in its default layout − The desktop has the following panels − Current Folder − This panel allows you to access the project folders and files. Command Window − This is the main area where commands can be entered at the command line. It is indicated by the command prompt (>>). Workspace − The workspace shows all the variables created and/or imported from files. Command History − This panel shows or return commands that are entered at the command line. Set up GNU Octave If you are willing to use Octave on your machine ( Linux, BSD, OS X or Windows ), then kindly download latest version from Download GNU Octave. You can check the given installation instructions for your machine. Print Page Previous Next Advertisements ”;