Author: Saim Khalid

  • Syntax

    The syntax rules of PHP are very similar to C Language. PHP is a server side scripting language. A PHP code is stored as a text file with “.php” extension. A “.php” file is essentially a web page with one or more blocks of PHP code interspersed in the HTML script. However, it must be opened in a browser with a HTTP protocol URL. In other words, if you double-click on the PHP file icon, it will be opened locally with the file protocol. For example, if you open the “index.php” file in the document root folder of your Apache server, it may just show the text of the PHP code. However, if you launch the Apache server and open the URL http://localhost/index.php, it displays the Apache home page.

    A “.php” file may contain HTML, CSS and JavaScript code blocks along with the PHP code. Hence, the PHP parser must differentiate between the PHP code from the other elements. When a “.php” file is opened in the web browser, the HTML engine renders the HTML/CSS/JavaScript part and escapes out of the HTML block as soon as the statements included in PHP tags are encountered. The PHP parser interpreter processes this block and returns the response to the browser.

    PHP Syntax

    PHP defines two methods of using tags for escaping the PHP code from HTML. Canonical PHP tags and Short-open (SGML-style) tags.

    Canonical PHP Tags

    The most universally effective PHP tag style is −

    <?php
       One or more PHP statements
    ?>

    If you use this style, you can be positive that your tags will always be correctly interpreted.

    Short-open (SGML-style) Tags

    Short or short-open tags look like this −

    <?php
    	One or more PHP statements
    ?>

    Short tags are, as one might expect, the shortest option. You must do one of two things to enable PHP to recognize the tags −

    • Choose the “–enable-short-tags” configuration option when you’re building PHP.
    • Set the “short_open_tag” setting in your php.ini file to on.
    short_open_tag=on
    

    This option must be disabled to parse XML with PHP because the same syntax is used for XML tags.

    The use of ASP-style tags −

    <%...%>

    and HTML script tags −

    <script language ="PHP">...</script>

    has been discontinued.

    Escaping from HTML

    The PHP parser ignores everything outside of a pair of opening and closing tags. Thus, a PHP file can have mixed content. This allows PHP to be embedded in HTML documents −

    <p>This is a HTML statement</p><?php echo This is a PHP statement.'; ?><p>This is another HTML statement.</p>

    A little advanced example of escaping using conditions is shown below −

    <?php if ($expression == true): ?>
       This HTML statement will be rendered.
    <?php else: ?>
       Otherwise this HTML statement will be rendered.
    <?php endif; ?>

    PHP skips the blocks where the condition is not met, even though they are outside of the PHP open/close tags.

    For outputting large blocks of text, dropping out of PHP parsing mode is generally more efficient than sending all of the text through echo or print.

    Basic Syntax of PHP

    The basic syntax of PHP is very similar to that of C and C++.

    Statements are expressions terminated by semicolons

    A statement in PHP is any expression that is followed by a semicolon (;). Any sequence of valid PHP statements that is enclosed by the PHP tags is a valid PHP program.

    Here is a typical statement in PHP, which in this case assigns a string of characters to a variable called “$greeting” −

    $greeting="Welcome to PHP!";

    A physical line in the text editor doesn’t have any significance in a PHP code. There may be multiple semicolon-terminated statements in a single line. On the other hand, a PHP statement may spill over more than one line if required.

    Expressions are combinations of tokens

    The smallest building blocks of PHP are the indivisible tokens such as numbers (3.14159), strings (“two”), variables ($two), constants (TRUE), and the special words that make up the syntax of PHP itself like “if”, “else”, “while”, “for”, and so forth.

    Braces make blocks

    Although statements cannot be combined like expressions, you can always put a sequence of statements anywhere a statement can go, by enclosing them in a set of curly braces.

    Here, both the following statements are equivalent −

    if(3==2+1)print("Good - I haven't totally lost my mind.");if(3==2+1){print("Good - I haven't totally");print("lost my mind.");}

    PHP is case sensitive

    PHP is a case sensitive language. The names of various PHP identifiers such as variable, function, class, etc., are case sensitive. As a result, the variable “$age” is not the same as “$Age”. Similarly, a function called “myfunction()” is different from another function called “MyFunction()”.

  • Features

    PHP (Hypertext Preprocessor) is an open-source server-side scripting language primarily used for web development. PHP can be embedded into HTML code.

    PHP is mainly used for server-side scripting, which runs scripts on the web server and then forwards the HTML they process to the web browser on the client. This makes it possible for programmers to design dynamic webpages that can manage sessions, handle forms, communicate with databases, and carry out a variety of other duties necessary for online applications.

    Features of PHP

    Over the years, PHP has incorporated numerous features. It is being consistently upgraded with new features and code revisions. In this chapter, let’s highlight some of the key features of PHP:

    PHP Features

    PHP is Simple and Easy to Learn

    The syntax of PHP compared to that of C, Java, and Perl, which makes it rather simple for developers to comprehend, particularly for those who are already familiar with other programming languages. Web apps can be developed quickly because of its generous pre-defined functions.

    PHP is Open Source

    PHP is free and open-source, meaning we can download it for free, and anyone can use it, modify it, and distribute. This encourages a sizable and vibrant developer community that uses forums, tutorials, and documentation to support and contribute to its development.

    PHP is Cross-Platform Compatible

    Numerous operating systems including Windows, Linux, macOS, and UNIX; and different databases like MongoDB, PostgreSQL, MySQL are compatible with PHP.

    PHP-based apps can operate on several environments without requiring any modifications due to this cross-platform inter-operability.

    Server-Side Scripting in PHP

    PHP is mainly used for server-side scripting, which runs scripts on the web server and then forwards the HTML they process to the web browser on the client. It helps the developers in Form Submission and Session Management with users across multiple requests.

    PHP Supports Easy Integration with Databases

    PHP offers strong database interaction support for various DBMS. It offers numerous built-in functions to achieve the database connection.

    PHP also includes database abstraction layer which integrates the communication between the application and the database. This makes it simple for developers to design database-driven web applications.

    PHP Provides Extensive Library Support

    PHP provides extensive libraries for various functionalities like image processing, encryption, PDF generation, parsing XML and JSON, handling sessions and cookies, and much more.

    Security Features in PHP

    PHP provides a plethora of built-in functions for data encryption. Developers can also leverage third-party applications for security.

    PHP employs security algorithms like Sha1 and MD5 to encrypt strings. Additionally, functions like filter_var and strip_tags contribute in maintaining a secure environment for the users. PHP also supports secure communication protocols like HTTPS.

    Efficient Memory and Session Management in PHP

    PHP is a reliable language due to its efficient memory management and session management. It avoids unnecessary memory allocation.

    PHP code runs in its own memory space which makes it faster compared to other scripting languages making it more efficient. In PHP, the database connections are also fast.

    PHP Has Active Community and Support

    Since PHP is an open-source platform, it has a vibrant community of developers who actively contribute to its development, share knowledge, provide support, and create third-party tools and frameworks.

    Due to this active community support, PHP remains up-to-date and developers can easily seek help from other community members in case they get any errors or exceptions while writing PHP codes.

  • History

    PHP started out as a small open-source project that evolved gradually as more and more people found out how useful it was. Rasmus Lerdorf released the first version of PHP way back in 1994. At that time, PHP stood for Personal Home Page, as he used it to maintain his personal homepage. Later on, he added database support and called it as “Personal Home Page/Forms Interpreter” or PHP/FI, which could be used to build simple, dynamic web applications.

    • Zeev Suraski and Andi Gutmans rewrote the parser in 1997 and formed the base of PHP 3. The name of the language was also changed to the recursive acronym PHP: Hypertext Preprocessor. They are also the authors of Zend Engine, a compiler and runtime environment for the PHP. Zend Engine powered PHP 4 was released in May 2000.
    • PHP 5 was released in 2004, which included many new features such as OOP support, the PHP Data Objects (PDO), and numerous performance enhancements.
    • PHP 7, is a new major PHP version which was developed in 2015. It included new language features, most notable being, the introduction of return type declarations for functions which complement the existing parameter type declarations, and support for the scalar types (integer, float, string, and boolean) in parameter and return type declarations.

    New Features in PHP 8

    PHP 8 is the latest major version, released in November 2020. Some of the new features and notable changes include:

    Just-in-time (JIT) Compilation

    PHP 8’s JIT compiler provides substantial performance improvements mathematical-type operations than for common web-development use cases. The JIT compiler provides the future potential to move some code from C to PHP.

    The “match: Expression

    The newly introduced “match” expression is more compact than a switch statement. Because match is an expression, its result can be assigned to a variable or returned from a function.

    PHP 8 – Type Changes and Additions

    PHP 8 introduced union types, a new static return type, and a new mixed type. PHP 8 also provided Attributes, (similar to “annotations” in other programming languages) that help in adding metadata to PHP classes.

    In addition, there have been many changes and additions to the PHP standard library. PHP 8.2.9 is the latest stable version available.

    Important milestones in PHP’s release history are summarized in the following table −

    VersionDescription
    Version 1.0
    (8 June 1995)
    Officially called “Personal Home Page Tools (PHP Tools)”. This is the first use of the name “PHP”.
    Version 2.0
    (1 November 1997)
    Officially called “PHP/FI 2.0”. This is the first release that could actually be characterised as PHP, being a standalone language with many features that have endured to the present day.
    Version 3.0
    (6 June 1998)
    Development moves from one person to multiple developers.Zeev Suraski and Andi Gutmans rewritten the base for this version.
    Version 4.0
    (22 May 2000)
    Added more advanced two-stage parse/execute tag-parsing system called the Zend engine.
    Version 5.0
    (13 July 2004)
    Zend Engine II with a new object model.
    Version 5.1
    (24 November 2005)
    Performance improvements with the introduction of compiler variables in re-engineered PHP Engine.Added PHP Data Objects (PDO) as a consistent interface for accessing databases.
    Version 6.x
    Not released
    Abandoned version of PHP that planned to include native Unicode support.
    Version 7.0
    (3 December 2015)
    Zend Engine 3 ,Uniform variable syntax,Added Closure:call(),?? (null coalesce) operator,Return type declarations,Scalar type declarations,<=> “spaceship” three-way comparison operator,Anonymous classes
    Version 7.3
    (6 December 2018)
    Flexible Heredoc and Nowdoc syntax
    Version 8.0
    (26 November 2020)
    Just-In-Time (JIT) compilation,Arrays starting with a negative index,TypeError on invalid arithmetic/bitwise operators,Variable syntax tweaks,Attributes,Named arguments,Match expression,Union types, Mixed type,Static return type
  • Installation

    You can start learning the basics of programming in PHP with the help of any of the online PHP compilers freely available on the Internet. This will help in getting acquainted with the features of PHP without installing it on your computer. Later on, install a full-fledged PHP environment on your local machine.

    One such online PHP compiler is provided by Tutorialpoint’s “Coding Ground for Developers”. Visit https://www.tutorialspoint.com/codingground.htm, enter PHP script and execute it.

    PHP Installation

    However, to be able to learn the advanced features of PHP, particularly related to the web concepts such as server variables, using backend databases, etc., you need to install the PHP environment on your local machine.

    In order to develop and run PHP Web pages, you neeed to install three vital components on your computer system.

    • Web Server − PHP will work with virtually all Web Server software, including Microsoft’s Internet Information Server (IIS), NGNIX, or Lighttpd etc. The most often used web server software is the freely available Apache Server. Download Apache for free here − https://httpd.apache.org/download.cgi
    • Database − PHP will work with virtually all database software, including Oracle and Sybase but most commonly used is freely available MySQL database. Download MySQL for free here − https://www.mysql.com/downloads/
    • PHP Parser − In order to process PHP script instructions a parser must be installed to generate HTML output that can be sent to the Web Browser.

    Although it is possible to install these three components separately, and configure the installation correctly, it is a little complex process, particularly for the beginners. Instead, using any all-in-one packaged distribution that contains precompiled Apache, MySQL and PHP binaries is convenient.

    XAMPP Installation

    There are many precompiled bundles available both in open-source as well as proprietary distributions. XAMPP, from Apache Friends (https://www.apachefriends.org/) is one of the most popular PHP enabled web server packages. We shall be using XAMPP in this tutorial.

    XAMPP is an easy to install Apache distribution that contains Apache, MariaDB, PHP and Perl. The letter X in the acronym indicates that it is a cross-platform software, available for use on Windows, Linux and OS X. Note that XAMPP includes MariaDB, which is a fork of MySQL, with no difference in its functionality.

    To download the respective installer for your operating system, visit https://www.apachefriends.org/download.html, and download one of the following −

    • Windows − https://sourceforge.net/projects/
    • Linux − https://sourceforge.net/projects/
    • OS X − https://sourceforge.net/projects/

    Using the installer on Windows is a completely wizard based installation. All you need to provide is an administrator access and the location of the installation directory which is “c:\xampp” by default.

    To install XAMPP on Linux, use the following steps −

    Step 1 − Change the permissions to the installer −

    chmod 755 xampp-linux-*-installer.run
    

    Run the installer −

    sudo ./xampp-linux-*-installer.run
    

    XAMPP is now installed below the “/opt/lamp” directory.

    Step 2 − To start XAMPP simply call this command −

    sudo /opt/lampp/lampp start
    

    You should now see something like this on your screen −

    Starting XAMPP...LAMPP: Starting Apache...LAMPP: Starting MySQL...LAMPP started.
    Ready. Apache and MySQL are running.

    You can also use a graphical tool to manage your servers easily. You can start this tool with the following commands −

    cd /opt/lampp
    sudo ./manager-linux.run(or manager-linux-x64.run)

    Step 3 − To stop XAMPP simply call this command −

    sudo /opt/lampp/lampp stop
    

    You should now see something like this on your screen −

    Stopping XAMPP...LAMPP: Stopping Apache...LAMPP: Stopping MySQL...LAMPP stopped.

    Also, note that there is a graphical tool that you can use to start/stop your servers easily. You can start this tool with the following commands −

    cd /opt/lampp
    sudo ./manager-linux.run(or manager-linux-x64.run)

    If you are using OS X, follow these steps −

    • To start the installation, Open the DMG-Image, and double-click the image to start the installation process.
    • To start XAMPP simply open XAMPP Control and start Apache, MySQL and ProFTPD. The name of the XAMPP Control is “manager-osx”.
    • To stop XAMPP simply open XAMPP Control and stop the servers. The name of the XAMPP Control is “manager-osx”.
    • The XAMPP control panel is a GUI tool from which the Apache server, and MySQL can be easily started and stopped.
    PHP Installation 2

    Press the Admin button after starting the Apache module. The XAMPP homepage appears like the one shown below −

    PHP Installation 3

    PHP Parser Installation

    Before you proceed it is important to make sure that you have proper environment setup on your machine to develop your web programs using PHP.

    Type the following address into your browser’s address box.

    http://127.0.0.1/info.php
    

    If this displays a page showing your PHP installation related information then it means you have PHP and Webserver installed properly. Otherwise you have to follow given procedure to install PHP on your computer.

    This section will guide you to install and configure PHP over the following four platforms −

    • PHP Installation on Linux or Unix with Apache
    • PHP Installation on Mac OS X with Apache
    • PHP Installation on Windows NT/2000/XP with IIS
    • PHP Installation on Windows NT/2000/XP with Apache

    Apache Configuration

    If you are using Apache as a Web Server then this section will guide you to edit Apache Configuration Files.

    Just Check it here − PHP Configuration in Apache Server

    PHP.INI File Configuration

    The PHP configuration file, php.ini, is the final and most immediate way to affect PHP’s functionality.

    Just Check it here − PHP.INI File Configuration

    Windows IIS Configuration

    To configure IIS on your Windows machine you can refer your IIS Reference Manual shipped along with IIS.

    You now have a complete PHP development environment on your local machine.

  • Introduction

    PHP started out as a small open source project that evolved as more and more people found out how useful it was. Rasmus Lerdorf released the first version of PHP way back in 1994. Initially, PHP was supposed to be an abbreviation for “Personal Home Page”, but it now stands for the recursive initialism “PHP: Hypertext Preprocessor”.

    Lerdorf began PHP development in 1993 by writing several Common Gateway Interface (CGI) programs in C, which he used to maintain in his personal homepage. Later on, He extended them to work with web forms and to communicate with databases. This implementation of PHP was “Personal Home Page/Forms Interpreter” or PHP/FI.

    Today, PHP is the world’s most popular server-side programming language for building web applications. Over the years, it has gone through successive revisions and versions.

    PHP Versions

    PHP was developed by Rasmus Lerdorf in 1994 as a simple set of CGI binaries written in C. He called this suite of scripts “Personal Home Page Tools”. It can be regarded as PHP version 1.0.

    • In April 1996, Rasmus introduced PHP/FI. Included built-in support for DBM, mSQL, and Postgres95 databases, cookies, user-defined function support. PHP/FI was given the version 2.0 status.
    • PHP: Hypertext Preprocessor – PHP 3.0 version came about when Zeev Suraski and Andi Gutmans rewrote the PHP parser and acquired the present-day acronym. It provided a mature interface for multiple databases, protocols and APIs, object-oriented programming support, and consistent language syntax.
    • PHP 4.0 was released in May 2000 powered by Zend Engine. It had support for many web servers, HTTP sessions, output buffering, secure ways of handling user input and several new language constructs.
    • PHP 5.0 was released in July 2004. It is mainly driven by its core, the Zend Engine 2.0 with a new object model and dozens of other new features. PHP’s development team includes dozens of developers and others working on PHP-related and supporting projects such as PEAR, PECL, and documentation.
    • PHP 7.0 was released in Dec 2015. This was originally dubbed PHP next generation (phpng). Developers reworked Zend Engine is called Zend Engine 3. Some of the important features of PHP 7 include its improved performance, reduced memory usage, Return and Scalar Type Declarations and Anonymous Classes.
    • PHP 8.0 was released on 26 November 2020. This is a major version having many significant improvements from its previous versions. One standout feature is Just-in-time compilation (JIT) that can provide substantial performance improvements. The latest version of PHP is 8.2.8, released on July 4th, 2023.

    PHP Application Areas

    PHP is one of the most widely used language over the web. Here are some of the application areas of PHP −

    • PHP is a server-side scripting language that is embedded in HTML. It is used to manage dynamic content, databases, session tracking, even build entire e-commerce sites. Although it is especially suited to web development, you can also build desktop standalone applications as PHP also has a command-line interface. You can use PHP-GTK extension to build GUI applications in PHP.
    • PHP is widely used for building web applications, but you are not limited to output only HTML. PHP’s ouput abilities include rich file types, such as images or PDF files, encrypting data, and sending emails. You can also output easily any text, such as JSON or XML.
    • PHP is a cross-platform language, capable of running on all major operating system platforms and with most of the web server programs such as Apache, IIS, lighttpd and nginx. PHP also supports other services using protocols such as LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM, etc.

    Here are some more important features of PHP −

    • PHP performs system functions. It can create, open, read, write, and close the files.
    • PHP can handle forms. It can gather data from files, save data to a file, through email you can send data, return data to the user.
    • You add, delete, modify elements within your database through PHP.
    • Access cookies variables and set cookies.
    • Using PHP, you can restrict users to access some pages of your website.
    • It can encrypt data.

    PHP provides a large number of reusable classes and libraries are available on “PEAR” and “Composer”. PEAR (PHP Extension and Application Repository) is a distribution system for reusable PHP libraries or classes. “Composer” is a dependency management tool in PHP.

  • Data Output

    Data export (or output) in MATLAB means to write into files. MATLAB allows you to use your data in another application that reads ASCII files. For this, MATLAB provides several data export options.

    You can create the following type of files −

    • Rectangular, delimited ASCII data file from an array.
    • Diary (or log) file of keystrokes and the resulting text output.
    • Specialized ASCII file using low-level functions such as fprintf.
    • MEX-file to access your C/C++ or Fortran routine that writes to a particular text file format.

    Apart from this, you can also export data to spreadsheets.

    There are two ways to export a numeric array as a delimited ASCII data file −

    • Using the save function and specifying the -ascii qualifier
    • Using the dlmwrite function

    Syntax for using the save function is −

    save my_data.out num_array -ascii
    

    where, my_data.out is the delimited ASCII data file created, num_array is a numeric array and −ascii is the specifier.

    Syntax for using the dlmwrite function is −

    dlmwrite('my_data.out', num_array, 'dlm_char')
    

    where, my_data.out is the delimited ASCII data file created, num_array is a numeric array and dlm_char is the delimiter character.

    Example

    The following example demonstrates the concept. Create a script file and type the following code −

    num_array = [ 1 2 3 4 ; 4 5 6 7; 7 8 9 0];
    save array_data1.out num_array -ascii;
    type array_data1.out
    dlmwrite('array_data2.out', num_array, ' ');
    type array_data2.out

    When you run the file, it displays the following result −

       1.0000000e+00   2.0000000e+00   3.0000000e+00   4.0000000e+00
       4.0000000e+00   5.0000000e+00   6.0000000e+00   7.0000000e+00
       7.0000000e+00   8.0000000e+00   9.0000000e+00   0.0000000e+00
    
    1 2 3 4
    4 5 6 7
    7 8 9 0
    

    Please note that the save -ascii command and the dlmwrite function does not work with cell arrays as input. To create a delimited ASCII file from the contents of a cell array, you can

    • Either, convert the cell array to a matrix using the cell2mat function
    • Or export the cell array using low-level file I/O functions.

    If you use the save function to write a character array to an ASCII file, it writes the ASCII equivalent of the characters to the file.

    For example, let us write the word ‘hello’ to a file −

    h = 'hello';
    save textdata.out h -ascii
    type textdata.out

    MATLAB executes the above statements and displays the following result. which is the characters of the string ‘hello’ in 8-digit ASCII format.

    1.0400000e+02   1.0100000e+02   1.0800000e+02   1.0800000e+02   1.1100000e+02
    

    Writing to Diary Files

    Diary files are activity logs of your MATLAB session. The diary function creates an exact copy of your session in a disk file, excluding graphics.

    To turn on the diary function, type −

    diary

    Optionally, you can give the name of the log file, say −

    diary logdata.out
    

    To turn off the diary function −

    diary off
    

    You can open the diary file in a text editor.

    Exporting Data to Text Data Files with Low-Level I/O

    So far, we have exported numeric arrays. However, you may need to create other text files, including combinations of numeric and character data, nonrectangular output files, or files with non-ASCII encoding schemes. For these purposes, MATLAB provides the low-level fprintf function.

    As in low-level I/O file activities, before exporting, you need to open or create a file with the fopen function and get the file identifier. By default, fopen opens a file for read-only access. You should specify the permission to write or append, such as ‘w’ or ‘a’.

    After processing the file, you need to close it with fclose(fid) function.

    The following example demonstrates the concept −

    Example

    Create a script file and type the following code in it −

    % create a matrix y, with two rows
    x = 0:10:100;
    y = [x; log(x)];
     
    % open a file for writing
    fid = fopen('logtable.txt', 'w');
     
    % Table Header
    fprintf(fid, 'Log     Function\n\n');
     
    % print values in column order
    % two values appear on each row of the file
    fprintf(fid, '%f    %f\n', y);
    fclose(fid);
    
    % display the file created
    type logtable.txt

    When you run the file, it displays the following result −

    Log         Function
    
    0.000000    -Inf
    10.000000    2.302585
    20.000000    2.995732
    30.000000    3.401197
    40.000000    3.688879
    50.000000    3.912023
    60.000000    4.094345
    70.000000    4.248495
    80.000000    4.382027
    90.000000    4.499810
    100.000000    4.605170
    
  • Data Import

    Importing data in MATLAB means loading data from an external file. The importdata function allows loading various data files of different formats. It has the following five forms −

    Sr.No.Function & Description
    1A = importdata(filename)Loads data into array A from the file denoted by filename.
    2A = importdata(‘-pastespecial’)Loads data from the system clipboard rather than from a file.
    3A = importdata(___, delimiterIn)Interprets delimiterIn as the column separator in ASCII file, filename, or the clipboard data. You can use delimiterIn with any of the input arguments in the above syntaxes.
    4A = importdata(___, delimiterIn, headerlinesIn)Loads data from ASCII file, filename, or the clipboard, reading numeric data starting from line headerlinesIn+1.
    5[A, delimiterOut, headerlinesOut] = importdata(___)Returns the detected delimiter character for the input ASCII file in delimiterOut and the detected number of header lines in headerlinesOut, using any of the input arguments in the previous syntaxes.

    By default, Octave does not have support for importdata() function, so you will have to search and install this package to make following examples work with your Octave installation.

    Example 1

    Let us load and display an image file. Create a script file and type the following code in it −

    filename = 'smile.jpg';
    A = importdata(filename);
    image(A);

    When you run the file, MATLAB displays the image file. However, you must store it in the current directory.

    Importing Imange Files

    Example 2

    In this example, we import a text file and specify Delimiter and Column Header. Let us create a space-delimited ASCII file with column headers, named weeklydata.txt.

    Our text file weeklydata.txt looks like this −

    SunDay  MonDay  TuesDay  WednesDay  ThursDay  FriDay  SaturDay
    95.01   76.21   61.54    40.57       55.79    70.28   81.53
    73.11   45.65   79.19    93.55       75.29    69.87   74.68
    60.68   41.85   92.18    91.69       81.32    90.38   74.51
    48.60   82.14   73.82    41.03       0.99     67.22   93.18
    89.13   44.47   57.63    89.36       13.89    19.88   46.60
    

    Create a script file and type the following code in it −

    filename = 'weeklydata.txt';
    delimiterIn = ' ';
    headerlinesIn = 1;
    A = importdata(filename,delimiterIn,headerlinesIn);
    
    % View data
    for k = [1:7]
       disp(A.colheaders{1, k})
       disp(A.data(:, k))
       disp(' ')
    end

    When you run the file, it displays the following result −

    SunDay
       95.0100
       73.1100
       60.6800
       48.6000
       89.1300
     
    MonDay
       76.2100
       45.6500
       41.8500
       82.1400
       44.4700
     
    TuesDay
       61.5400
       79.1900
       92.1800
       73.8200
       57.6300
    
    WednesDay
       40.5700
       93.5500
       91.6900
       41.0300
       89.3600
     
    ThursDay
       55.7900
       75.2900
       81.3200
       0.9900
       13.8900
     
    FriDay
       70.2800
       69.8700
       90.3800
       67.2200
       19.8800
    
    SaturDay
       81.5300
       74.6800
       74.5100
       93.1800
       46.6000
    

    Example 3

    In this example, let us import data from clipboard.

    Copy the following lines to the clipboard −

    Mathematics is simple

    Create a script file and type the following code −

    A = importdata('-pastespecial')
    

    When you run the file, it displays the following result −

    A = 
       'Mathematics is simple'
    

    Low-Level File I/O

    The importdata function is a high-level function. The low-level file I/O functions in MATLAB allow the most control over reading or writing data to a file. However, these functions need more detailed information about your file to work efficiently.

    MATLAB provides the following functions for read and write operations at the byte or character level −

    FunctionDescription
    fcloseClose one or all open files
    feofTest for end-of-file
    ferrorInformation about file I/O errors
    fgetlRead line from file, removing newline characters
    fgetsRead line from file, keeping newline characters
    fopenOpen file, or obtain information about open files
    fprintfWrite data to text file
    freadRead data from binary file
    frewindMove file position indicator to beginning of open file
    fscanfRead data from text file
    fseekMove to specified position in file
    ftellPosition in open file
    fwriteWrite data to binary file

    Import Text Data Files with Low-Level I/O

    MATLAB provides the following functions for low-level import of text data files −

    • The fscanf function reads formatted data in a text or ASCII file.
    • The fgetl and fgets functions read one line of a file at a time, where a newline character separates each line.
    • The fread function reads a stream of data at the byte or bit level.

    Example

    We have a text data file ‘myfile.txt’ saved in our working directory. The file stores rainfall data for three months; June, July and August for the year 2012.

    The data in myfile.txt contains repeated sets of time, month and rainfall measurements at five places. The header data stores the number of months M; so we have M sets of measurements.

    The file looks like this −

    Rainfall Data
    Months: June, July, August
     
    M = 3
    12:00:00
    June-2012
    17.21  28.52  39.78  16.55 23.67
    19.15  0.35   17.57  NaN   12.01
    17.92  28.49  17.40  17.06 11.09
    9.59   9.33   NaN    0.31  0.23 
    10.46  13.17  NaN    14.89 19.33
    20.97  19.50  17.65  14.45 14.00
    18.23  10.34  17.95  16.46 19.34
    09:10:02
    July-2012
    12.76  16.94  14.38  11.86 16.89
    20.46  23.17  NaN    24.89 19.33
    30.97  49.50  47.65  24.45 34.00
    18.23  30.34  27.95  16.46 19.34
    30.46  33.17  NaN    34.89  29.33
    30.97  49.50  47.65  24.45 34.00
    28.67  30.34  27.95  36.46 29.34
    15:03:40
    August-2012
    17.09  16.55  19.59  17.25 19.22
    17.54  11.45  13.48  22.55 24.01
    NaN    21.19  25.85  25.05 27.21
    26.79  24.98  12.23  16.99 18.67
    17.54  11.45  13.48  22.55 24.01
    NaN    21.19  25.85  25.05 27.21
    26.79  24.98  12.23  16.99 18.67
    

    We will import data from this file and display this data. Take the following steps −

    • Open the file with fopen function and get the file identifier.
    • Describe the data in the file with format specifiers, such as ‘%s‘ for a string, ‘%d‘ for an integer, or ‘%f‘ for a floating-point number.
    • To skip literal characters in the file, include them in the format description. To skip a data field, use an asterisk (‘*’) in the specifier.For example, to read the headers and return the single value for M, we write −M = fscanf(fid, ‘%*s %*s\n%*s %*s %*s %*s\nM=%d\n\n’, 1);
    • By default, fscanf reads data according to our format description until it does not find any match for the data, or it reaches the end of the file. Here we will use for loop for reading 3 sets of data and each time, it will read 7 rows and 5 columns.
    • We will create a structure named mydata in the workspace to store data read from the file. This structure has three fields – timemonth, and raindata array.

    Create a script file and type the following code in it −

    filename = '/data/myfile.txt';
    rows = 7;
    cols = 5;
     
    % open the file
    fid = fopen(filename);
     
    % read the file headers, find M (number of months)
    M = fscanf(fid, '%*s %*s\n%*s %*s %*s %*s\nM=%d\n\n', 1);
     
    % read each set of measurements
    for n = 1:M
       mydata(n).time = fscanf(fid, '%s', 1);
       mydata(n).month = fscanf(fid, '%s', 1);
     
       % fscanf fills the array in column order,
       % so transpose the results
       mydata(n).raindata  = ...
    
      fscanf(fid, '%f', &#91;rows, cols]);
    end for n = 1:M disp(mydata(n).time), disp(mydata(n).month) disp(mydata(n).raindata) end % close the file fclose(fid);

    When you run the file, it displays the following result −

    12:00:00
    June-2012
       17.2100   17.5700   11.0900   13.1700   14.4500
       28.5200       NaN    9.5900       NaN   14.0000
       39.7800   12.0100    9.3300   14.8900   18.2300
       16.5500   17.9200       NaN   19.3300   10.3400
       23.6700   28.4900    0.3100   20.9700   17.9500
       19.1500   17.4000    0.2300   19.5000   16.4600
       0.3500   17.0600   10.4600   17.6500   19.3400
    
    09:10:02
    July-2012
       12.7600       NaN   34.0000   33.1700   24.4500
       16.9400   24.8900   18.2300       NaN   34.0000
       14.3800   19.3300   30.3400   34.8900   28.6700
       11.8600   30.9700   27.9500   29.3300   30.3400
       16.8900   49.5000   16.4600   30.9700   27.9500
       20.4600   47.6500   19.3400   49.5000   36.4600
       23.1700   24.4500   30.4600   47.6500   29.3400
    
    15:03:40
    August-2012
       17.0900   13.4800   27.2100   11.4500   25.0500
       16.5500   22.5500   26.7900   13.4800   27.2100
       19.5900   24.0100   24.9800   22.5500   26.7900
       17.2500       NaN   12.2300   24.0100   24.9800
       19.2200   21.1900   16.9900       NaN   12.2300
       17.5400   25.8500   18.6700   21.1900   16.9900
       11.4500   25.0500   17.5400   25.8500   18.6700
    
  • Functions

    A function is a group of statements that together perform a task. In MATLAB, functions are defined in separate files. The name of the file and of the function should be the same.

    Functions operate on variables within their own workspace, which is also called the local workspace, separate from the workspace you access at the MATLAB command prompt which is called the base workspace.

    Functions can accept more than one input arguments and may return more than one output arguments.

    Syntax of a function statement is −

    function [out1,out2, ..., outN] = myfun(in1,in2,in3, ..., inN)
    

    Example

    The following function named mymax should be written in a file named mymax.m. It takes five numbers as argument and returns the maximum of the numbers.

    Create a function file, named mymax.m and type the following code in it −

    function max = mymax(n1, n2, n3, n4, n5)
    
    %This function calculates the maximum of the
    % five numbers given as input
    max =  n1;
    if(n2 > max)
       max = n2;
    end
    if(n3 > max)
       max = n3;
    end
    if(n4 > max)
       max = n4;
    end
    if(n5 > max)
       max = n5;
    end

    The first line of a function starts with the keyword function. It gives the name of the function and order of arguments. In our example, the mymax function has five input arguments and one output argument.

    The comment lines that come right after the function statement provide the help text. These lines are printed when you type −

    help mymax
    

    MATLAB will execute the above statement and return the following result −

    This function calculates the maximum of the
       five numbers given as input
    

    You can call the function as −

    mymax(34, 78, 89, 23, 11)
    

    MATLAB will execute the above statement and return the following result −

    ans = 89
    

    Anonymous Functions

    An anonymous function is like an inline function in traditional programming languages, defined within a single MATLAB statement. It consists of a single MATLAB expression and any number of input and output arguments.

    You can define an anonymous function right at the MATLAB command line or within a function or script.

    This way you can create simple functions without having to create a file for them.

    The syntax for creating an anonymous function from an expression is

    f = @(arglist)expression
    

    Example

    In this example, we will write an anonymous function named power, which will take two numbers as input and return first number raised to the power of the second number.

    Create a script file and type the following code in it −

    power = @(x, n) x.^n;
    result1 = power(7, 3)
    result2 = power(49, 0.5)
    result3 = power(10, -10)
    result4 = power (4.5, 1.5)

    When you run the file, it displays −

    result1 =  343
    result2 =  7
    result3 =  1.0000e-10
    result4 =  9.5459
    

    Primary and Sub-Functions

    Any function other than an anonymous function must be defined within a file. Each function file contains a required primary function that appears first and any number of optional sub-functions that comes after the primary function and used by it.

    Primary functions can be called from outside of the file that defines them, either from command line or from other functions, but sub-functions cannot be called from command line or other functions, outside the function file.

    Sub-functions are visible only to the primary function and other sub-functions within the function file that defines them.

    Example

    Let us write a function named quadratic that would calculate the roots of a quadratic equation. The function would take three inputs, the quadratic co-efficient, the linear co-efficient and the constant term. It would return the roots.

    The function file quadratic.m will contain the primary function quadratic and the sub-function disc, which calculates the discriminant.

    Create a function file quadratic.m and type the following code in it −

    function [x1,x2] = quadratic(a,b,c)
    
    %this function returns the roots of 
    % a quadratic equation.
    % It takes 3 input arguments
    % which are the co-efficients of x2, x and the 
    %constant term
    % It returns the roots
    d = disc(a,b,c); 
    x1 = (-b + d) / (2*a);
    x2 = (-b - d) / (2*a);
    end   % end of quadratic
    
    function dis = disc(a,b,c) 
    %function calculates the discriminant
    dis = sqrt(b^2 - 4*a*c);
    end   % end of sub-function

    You can call the above function from command prompt as −

    quadratic(2,4,-4)

    MATLAB will execute the above statement and return the following result −

    ans = 0.7321
    

    Nested Functions

    You can define functions within the body of another function. These are called nested functions. A nested function contains any or all of the components of any other function.

    Nested functions are defined within the scope of another function and they share access to the containing function’s workspace.

    A nested function follows the following syntax −

    function x = A(p1, p2)
    ...
    B(p2)
       function y = B(p3)
       ...
       end
    ...
    end
    

    Example

    Let us rewrite the function quadratic, from previous example, however, this time the disc function will be a nested function.

    Create a function file quadratic2.m and type the following code in it −

    function [x1,x2] = quadratic2(a,b,c)
    function disc  % nested function
    d = sqrt(b^2 - 4*a*c);
    end   % end of function disc
    
    disc;
    x1 = (-b + d) / (2*a);
    x2 = (-b - d) / (2*a);
    end   % end of function quadratic2

    You can call the above function from command prompt as −

    quadratic2(2,4,-4)

    MATLAB will execute the above statement and return the following result −

    ans =  0.73205
    

    Private Functions

    A private function is a primary function that is visible only to a limited group of other functions. If you do not want to expose the implementation of a function(s), you can create them as private functions.

    Private functions reside in subfolders with the special name private.

    They are visible only to functions in the parent folder.

    Example

    Let us rewrite the quadratic function. This time, however, the disc function calculating the discriminant, will be a private function.

    Create a subfolder named private in working directory. Store the following function file disc.m in it −

    function dis = disc(a,b,c) 
    %function calculates the discriminant
    dis = sqrt(b^2 - 4*a*c);
    end      % end of sub-function

    Create a function quadratic3.m in your working directory and type the following code in it −

    function [x1,x2] = quadratic3(a,b,c)
    
    %this function returns the roots of 
    % a quadratic equation.
    % It takes 3 input arguments
    % which are the co-efficient of x2, x and the 
    %constant term
    % It returns the roots
    d = disc(a,b,c); 
    
    x1 = (-b + d) / (2*a);
    x2 = (-b - d) / (2*a);
    end      % end of quadratic3

    You can call the above function from command prompt as −

    quadratic3(2,4,-4)

    MATLAB will execute the above statement and return the following result −

    ans =  0.73205
    

    Global Variables

    Global variables can be shared by more than one function. For this, you need to declare the variable as global in all the functions.

    If you want to access that variable from the base workspace, then declare the variable at the command line.

    The global declaration must occur before the variable is actually used in a function. It is a good practice to use capital letters for the names of global variables to distinguish them from other variables.

    Example

    Let us create a function file named average.m and type the following code in it −

    function avg = average(nums)
    global TOTAL
    avg = sum(nums)/TOTAL;
    end

    Create a script file and type the following code in it −

    global TOTAL;
    TOTAL = 10;
    n = [34, 45, 25, 45, 33, 19, 40, 34, 38, 42];
    av = average(n)

    When you run the file, it will display the following result −

    av =  35.500
    
  • Strings

    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 −

    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      1x16               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 −

    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 −

    doc_profile = ['Zara Ali                             '; ...
    
               'Sr. Surgeon                          '; ...
               'R N Tagore Cardiology Research Center']
    doc_profile = char('Zara Ali', 'Sr. Surgeon', ...
                  'RN Tagore Cardiology Research Center')</code></pre>

    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 −

    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 −

    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 −

    FunctionPurpose
    Functions for storing text in character arrays, combine character arrays, etc.
    blanksCreate string of blank characters
    cellstrCreate cell array of strings from character array
    charConvert to character array (string)
    iscellstrDetermine whether input is cell array of strings
    ischarDetermine whether item is character array
    sprintfFormat data into string
    strcatConcatenate strings horizontally
    strjoinJoin strings in cell array into single string
    Functions for identifying parts of strings, find and replace substrings
    ischarDetermine whether item is character array
    isletterArray elements that are alphabetic letters
    isspaceArray elements that are space characters
    isstrpropDetermine whether string is of specified category
    sscanfRead formatted data from string
    strfindFind one string within another
    strrepFind and replace substring
    strsplitSplit string at specified delimiter
    strtokSelected parts of string
    validatestringCheck validity of text string
    symvarDetermine symbolic variables in expression
    regexpMatch regular expression (case sensitive)
    regexpiMatch regular expression (case insensitive)
    regexprepReplace string using regular expression
    regexptranslateTranslate string into regular expression
    Functions for string comparison
    strcmpCompare strings (case sensitive)
    strcmpiCompare strings (case insensitive)
    strncmpCompare first n characters of strings (case sensitive)
    strncmpiCompare first n characters of strings (case insensitive)
    Functions for changing string to upper- or lowercase, creating or removing white space
    deblankStrip trailing blanks from end of string
    strtrimRemove leading and trailing white space from string
    lowerConvert string to lowercase
    upperConvert string to uppercase
    strjustJustify character array

    Examples

    The following examples illustrate some of the above-mentioned string functions −

    Formatting Strings

    Create a script file and type the following code into it −

    A = pi*1000*ones(1,5);
    sprintf(' %f \n %.2f \n %+.2f \n %12.2f \n %012.2f \n', A)

    When you run the file, it displays the following result −

    ans =  3141.592654 
       3141.59 
       +3141.59 
    
      3141.59 
    000003141.59

    Joining Strings

    Create a script file and type the following code into it −

    %cell array of strings
    str_array = {'red','blue','green', 'yellow', 'orange'};
    
    % Join strings in cell array into single string
    str1 = strjoin(str_array, "-")
    str2 = strjoin(str_array, ",")

    When you run the file, it displays the following result −

    str1 = red-blue-green-yellow-orange
    str2 = red,blue,green,yellow,orange
    

    Finding and Replacing Strings

    Create a script file and type the following code into it −

    students = {'Zara Ali', 'Neha Bhatnagar', ...
    
            'Monica Malik', 'Madhu Gautam', ...
            'Madhu Sharma', 'Bhawna Sharma',...
            'Nuha Ali', 'Reva Dutta', ...
            'Sunaina Ali', 'Sofia Kabir'};
    % The strrep function searches and replaces sub-string. new_student = strrep(students(8), 'Reva', 'Poulomi') % Display first names first_names = strtok(students)

    When you run the file, it displays the following result −

    new_student = 
    {
       [1,1] = Poulomi Dutta
    }
    first_names = 
    {
       [1,1] = Zara
       [1,2] = Neha
       [1,3] = Monica
       [1,4] = Madhu
       [1,5] = Madhu
       [1,6] = Bhawna
       [1,7] = Nuha
       [1,8] = Reva
       [1,9] = Sunaina
       [1,10] = Sofia
    }
    

    Comparing Strings

    Create a script file and type the following code into it −

    str1 = 'This is test'
    str2 = 'This is text'
    if (strcmp(str1, str2))
       sprintf('%s and %s are equal', str1, str2)
    else
       sprintf('%s and %s are not equal', str1, str2)
    end

    When you run the file, it displays the following result −

    str1 = This is test
    str2 = This is text
    ans = This is test and This is text are not equal
    
  • Numbers

    MATLAB supports various numeric classes that include signed and unsigned integers and single-precision and double-precision floating-point numbers. By default, MATLAB stores all numeric values as double-precision floating point numbers.

    You can choose to store any number or array of numbers as integers or as single-precision numbers.

    All numeric types support basic array operations and mathematical operations.

    Conversion to Various Numeric Data Types

    MATLAB provides the following functions to convert to various numeric data types −

    FunctionPurpose
    doubleConverts to double precision number
    singleConverts to single precision number
    int8Converts to 8-bit signed integer
    int16Converts to 16-bit signed integer
    int32Converts to 32-bit signed integer
    int64Converts to 64-bit signed integer
    uint8Converts to 8-bit unsigned integer
    uint16Converts to 16-bit unsigned integer
    uint32Converts to 32-bit unsigned integer
    uint64Converts to 64-bit unsigned integer

    Example

    Create a script file and type the following code −

    x = single([5.32 3.47 6.28]) .* 7.5
    x = double([5.32 3.47 6.28]) .* 7.5
    x = int8([5.32 3.47 6.28]) .* 7.5
    x = int16([5.32 3.47 6.28]) .* 7.5
    x = int32([5.32 3.47 6.28]) .* 7.5
    x = int64([5.32 3.47 6.28]) .* 7.5

    When you run the file, it shows the following result −

    x =
    
       39.900   26.025   47.100
    
    x =
    
       39.900   26.025   47.100
    
    x =
    
       38  23  45
    
    x =
    
       38  23  45
    
    x =
    
       38  23  45
    
    x =
    
       38  23  45
    

    Example

    Let us extend the previous example a little more. Create a script file and type the following code −

    x = int32([5.32 3.47 6.28]) .* 7.5
    x = int64([5.32 3.47 6.28]) .* 7.5
    x = num2cell(x)

    When you run the file, it shows the following result −

    x =
    
       38  23  45
    
    x =
    
       38  23  45
    
    x = 
    {
       [1,1] = 38
       [1,2] = 23
       [1,3] = 45
    }
    

    Smallest and Largest Integers

    The functions intmax() and intmin() return the maximum and minimum values that can be represented with all types of integer numbers.

    Both the functions take the integer data type as the argument, for example, intmax(int8) or intmin(int64) and return the maximum and minimum values that you can represent with the integer data type.

    Example

    The following example illustrates how to obtain the smallest and largest values of integers. Create a script file and write the following code in it −

    % displaying the smallest and largest signed integer data
    str = 'The range for int8 is:\n\t%d to %d ';
    sprintf(str, intmin('int8'), intmax('int8'))
    
    str = 'The range for int16 is:\n\t%d to %d ';
    sprintf(str, intmin('int16'), intmax('int16'))
    
    str = 'The range for int32 is:\n\t%d to %d ';
    sprintf(str, intmin('int32'), intmax('int32'))
    
    str = 'The range for int64 is:\n\t%d to %d ';
    sprintf(str, intmin('int64'), intmax('int64'))
     
    % displaying the smallest and largest unsigned integer data
    str = 'The range for uint8 is:\n\t%d to %d ';
    sprintf(str, intmin('uint8'), intmax('uint8'))
    
    str = 'The range for uint16 is:\n\t%d to %d ';
    sprintf(str, intmin('uint16'), intmax('uint16'))
    
    str = 'The range for uint32 is:\n\t%d to %d ';
    sprintf(str, intmin('uint32'), intmax('uint32'))
    
    str = 'The range for uint64 is:\n\t%d to %d ';
    sprintf(str, intmin('uint64'), intmax('uint64'))

    When you run the file, it shows the following result −

    ans = The range for int8 is:
    	-128 to 127 
    ans = The range for int16 is:
    	-32768 to 32767 
    ans = The range for int32 is:
    	-2147483648 to 2147483647 
    ans = The range for int64 is:
    	0 to 0 
    ans = The range for uint8 is:
    	0 to 255 
    ans = The range for uint16 is:
    	0 to 65535 
    ans = The range for uint32 is:
    	0 to -1 
    ans = The range for uint64 is:
    	0 to 18446744073709551616 
    

    Smallest and Largest Floating Point Numbers

    The functions realmax() and realmin() return the maximum and minimum values that can be represented with floating point numbers.

    Both the functions when called with the argument ‘single’, return the maximum and minimum values that you can represent with the single-precision data type and when called with the argument ‘double’, return the maximum and minimum values that you can represent with the double-precision data type.

    Example

    The following example illustrates how to obtain the smallest and largest floating point numbers. Create a script file and write the following code in it −

    % displaying the smallest and largest single-precision 
    % floating point number
    str = 'The range for single is:\n\t%g to %g and\n\t %g to  %g';
    sprintf(str, -realmax('single'), -realmin('single'), ...
       realmin('single'), realmax('single'))
    
    % displaying the smallest and largest double-precision 
    % floating point number
    str = 'The range for double is:\n\t%g to %g and\n\t %g to  %g';
    sprintf(str, -realmax('double'), -realmin('double'), ...
       realmin('double'), realmax('double'))

    When you run the file, it displays the following result −

    ans = The range for single is:                                                  
    
        -3.40282e+38 to -1.17549e-38 and                                        
         1.17549e-38 to  3.40282e+38                                            
    ans = The range for double is:
        -1.79769e+308 to -2.22507e-308 and                                      
         2.22507e-308 to  1.79769e+308</code></pre>