MATLAB – Variables ”; Previous Next In MATLAB environment, every variable is an array or matrix. You can assign variables in a simple way. For example, Live Demo x = 3 % defining x and initializing it with a value MATLAB will execute the above statement and return the following result − x = 3 It creates a 1-by-1 matrix named x and stores the value 3 in its element. Let us check another example, Live Demo x = sqrt(16) % defining x and initializing it with an expression MATLAB will execute the above statement and return the following result − x = 4 Please note that − Once a variable is entered into the system, you can refer to it later. Variables must have values before they are used. When an expression returns a result that is not assigned to any variable, the system assigns it to a variable named ans, which can be used later. For example, Live Demo sqrt(78) MATLAB will execute the above statement and return the following result − ans = 8.8318 You can use this variable ans − Live Demo sqrt(78); 9876/ans MATLAB will execute the above statement and return the following result − ans = 1118.2 Let”s look at another example − Live Demo x = 7 * 8; y = x * 7.89 MATLAB will execute the above statement and return the following result − y = 441.84 Multiple Assignments You can have multiple assignments on the same line. For example, Live Demo a = 2; b = 7; c = a * b MATLAB will execute the above statement and return the following result − c = 14 I have forgotten the Variables! The who command displays all the variable names you have used. who MATLAB will execute the above statement and return the following result − Your variables are: a ans b c The whos command displays little more about the variables − Variables currently in memory Type of each variables Memory allocated to each variable Whether they are complex variables or not whos MATLAB will execute the above statement and return the following result − Attr Name Size Bytes Class ==== ==== ==== ==== ===== a 1×1 8 double ans 1×70 757 cell b 1×1 8 double c 1×1 8 double Total is 73 elements using 781 bytes The clear command deletes all (or the specified) variable(s) from the memory. clear x % it will delete x, won”t display anything clear % it will delete all variables in the workspace % peacefully and unobtrusively Long Assignments Long assignments can be extended to another line by using an ellipses (…). For example, Live Demo initial_velocity = 0; acceleration = 9.8; time = 20; final_velocity = initial_velocity + acceleration * time MATLAB will execute the above statement and return the following result − final_velocity = 196 The format Command By default, MATLAB displays numbers with four decimal place values. This is known as short format. However, if you want more precision, you need to use the format command. The format long command displays 16 digits after decimal. For example − Live Demo format long x = 7 + 10/3 + 5 ^ 1.2 MATLAB will execute the above statement and return the following result− x = 17.2319816406394 Another example, Live Demo format short x = 7 + 10/3 + 5 ^ 1.2 MATLAB will execute the above statement and return the following result − x = 17.232 The format bank command rounds numbers to two decimal places. For example, Live Demo format bank daily_wage = 177.45; weekly_wage = daily_wage * 6 MATLAB will execute the above statement and return the following result − weekly_wage = 1064.70 MATLAB displays large numbers using exponential notation. The format short e command allows displaying in exponential form with four decimal places plus the exponent. For example, Live Demo format short e 4.678 * 4.9 MATLAB will execute the above statement and return the following result − ans = 2.2922e+01 The format long e command allows displaying in exponential form with four decimal places plus the exponent. For example, Live Demo format long e x = pi MATLAB will execute the above statement and return the following result − x = 3.141592653589793e+00 The format rat command gives the closest rational expression resulting from a calculation. For example, Live Demo format rat 4.678 * 4.9 MATLAB will execute the above statement and return the following result − ans = 34177/1491 Creating Vectors A vector is a one-dimensional array of numbers. MATLAB allows creating two types of vectors − Row vectors Column vectors Row vectors are created by enclosing the set of elements in square brackets, using space or comma to delimit the elements. For example, Live Demo r = [7 8 9 10 11] MATLAB will execute the above statement and return the following result − r = 7 8 9 10 11 Another example, Live Demo r = [7 8 9 10 11]; t = [2, 3, 4, 5, 6]; res = r + t MATLAB will execute the above statement and return the following result − res = 9 11 13 15 17 Column vectors are created by enclosing the set of elements in square brackets, using semicolon(;) to delimit the elements. Live Demo c = [7; 8; 9; 10; 11] MATLAB will execute the above statement and return the following result − c = 7 8 9 10 11 Creating Matrices A matrix is a two-dimensional array of numbers. In MATLAB, a matrix is created by entering each row as a sequence of space or comma separated elements, and end of a row is demarcated by a semicolon. For example, let us create a 3-by-3 matrix as − Live Demo m = [1 2 3; 4 5 6; 7 8 9] MATLAB will execute the above statement and return the following result − m = 1 2 3 4 5 6 7 8 9 Print Page
Category: matlab
MATLAB – Data Import
MATLAB – Data Import ”; Previous Next 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 1 A = importdata(filename) Loads data into array A from the file denoted by filename. 2 A = importdata(”-pastespecial”) Loads data from the system clipboard rather than from a file. 3 A = 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. 4 A = 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. 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 − Function Description fclose Close one or all open files feof Test for end-of-file ferror Information about file I/O errors fgetl Read line from file, removing newline characters fgets Read line from file, keeping newline characters fopen Open file, or obtain information about open files fprintf Write data to text file fread Read data from binary file frewind Move file position indicator to beginning of open file fscanf Read data from text file fseek Move to specified position in file ftell Position in open file fwrite Write 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 %*sn%*s %*s %*s %*snM=%dnn”, 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
MATLAB – Overview
MATLAB – Overview ”; Previous Next MATLAB (matrix laboratory) is a fourth-generation high-level programming language and interactive environment for numerical computation, visualization and programming. MATLAB is developed by MathWorks. It allows matrix manipulations; plotting of functions and data; implementation of algorithms; creation of user interfaces; interfacing with programs written in other languages, including C, C++, Java, and FORTRAN; analyze data; develop algorithms; and create models and applications. It has numerous built-in commands and math functions that help you in mathematical calculations, generating plots, and performing numerical methods. MATLAB”s Power of Computational Mathematics MATLAB is used in every facet of computational mathematics. Following are some commonly used mathematical calculations where it is used most commonly − Dealing with Matrices and Arrays 2-D and 3-D Plotting and graphics Linear Algebra Algebraic Equations Non-linear Functions Statistics Data Analysis Calculus and Differential Equations Numerical Calculations Integration Transforms Curve Fitting Various other special functions Features of MATLAB Following are the basic features of MATLAB − It is a high-level language for numerical computation, visualization and application development. It also provides an interactive environment for iterative exploration, design and problem solving. It provides vast library of mathematical functions for linear algebra, statistics, Fourier analysis, filtering, optimization, numerical integration and solving ordinary differential equations. It provides built-in graphics for visualizing data and tools for creating custom plots. MATLAB”s programming interface gives development tools for improving code quality maintainability and maximizing performance. It provides tools for building applications with custom graphical interfaces. It provides functions for integrating MATLAB based algorithms with external applications and languages such as C, Java, .NET and Microsoft Excel. Uses of MATLAB MATLAB is widely used as a computational tool in science and engineering encompassing the fields of physics, chemistry, math and all engineering streams. It is used in a range of applications including − Signal Processing and Communications Image and Video Processing Control Systems Test and Measurement Computational Finance Computational Biology Print Page Previous Next Advertisements ”;
MATLAB – Arrays
MATLAB – Arrays ”; Previous Next All variables of all data types in MATLAB are multidimensional arrays. A vector is a one-dimensional array and a matrix is a two-dimensional array. We have already discussed vectors and matrices. In this chapter, we will discuss multidimensional arrays. However, before that, let us discuss some special types of arrays. Special Arrays in MATLAB In this section, we will discuss some functions that create some special arrays. For all these functions, a single argument creates a square array, double arguments create rectangular array. The zeros() function creates an array of all zeros − For example − Live Demo zeros(5) MATLAB will execute the above statement and return the following result − ans = 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 The ones() function creates an array of all ones − For example − Live Demo ones(4,3) MATLAB will execute the above statement and return the following result − ans = 1 1 1 1 1 1 1 1 1 1 1 1 The eye() function creates an identity matrix. For example − Live Demo eye(4) MATLAB will execute the above statement and return the following result − ans = 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 The rand() function creates an array of uniformly distributed random numbers on (0,1) − For example − Live Demo rand(3, 5) MATLAB will execute the above statement and return the following result − ans = 0.8147 0.9134 0.2785 0.9649 0.9572 0.9058 0.6324 0.5469 0.1576 0.4854 0.1270 0.0975 0.9575 0.9706 0.8003 A Magic Square A magic square is a square that produces the same sum, when its elements are added row-wise, column-wise or diagonally. The magic() function creates a magic square array. It takes a singular argument that gives the size of the square. The argument must be a scalar greater than or equal to 3. Live Demo magic(4) MATLAB will execute the above statement and return the following result − ans = 16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1 Multidimensional Arrays An array having more than two dimensions is called a multidimensional array in MATLAB. Multidimensional arrays in MATLAB are an extension of the normal two-dimensional matrix. Generally to generate a multidimensional array, we first create a two-dimensional array and extend it. For example, let”s create a two-dimensional array a. Live Demo a = [7 9 5; 6 1 9; 4 3 2] MATLAB will execute the above statement and return the following result − a = 7 9 5 6 1 9 4 3 2 The array a is a 3-by-3 array; we can add a third dimension to a, by providing the values like − Live Demo a(:, :, 2)= [ 1 2 3; 4 5 6; 7 8 9] MATLAB will execute the above statement and return the following result − a = ans(:,:,1) = 0 0 0 0 0 0 0 0 0 ans(:,:,2) = 1 2 3 4 5 6 7 8 9 We can also create multidimensional arrays using the ones(), zeros() or the rand() functions. For example, Live Demo b = rand(4,3,2) MATLAB will execute the above statement and return the following result − b(:,:,1) = 0.0344 0.7952 0.6463 0.4387 0.1869 0.7094 0.3816 0.4898 0.7547 0.7655 0.4456 0.2760 b(:,:,2) = 0.6797 0.4984 0.2238 0.6551 0.9597 0.7513 0.1626 0.3404 0.2551 0.1190 0.5853 0.5060 We can also use the cat() function to build multidimensional arrays. It concatenates a list of arrays along a specified dimension − Syntax for the cat() function is − B = cat(dim, A1, A2…) Where, B is the new array created A1, A2, … are the arrays to be concatenated dim is the dimension along which to concatenate the arrays Example Create a script file and type the following code into it − Live Demo a = [9 8 7; 6 5 4; 3 2 1]; b = [1 2 3; 4 5 6; 7 8 9]; c = cat(3, a, b, [ 2 3 1; 4 7 8; 3 9 0]) When you run the file, it displays − c(:,:,1) = 9 8 7 6 5 4 3 2 1 c(:,:,2) = 1 2 3 4 5 6 7 8 9 c(:,:,3) = 2 3 1 4 7 8 3 9 0 Array Functions MATLAB provides the following functions to sort, rotate, permute, reshape, or shift array contents. Function Purpose length Length of vector or largest array dimension ndims Number of array dimensions numel Number of array elements size Array dimensions iscolumn Determines whether input is column vector isempty Determines whether array is empty ismatrix Determines whether input is matrix isrow Determines whether input is row vector isscalar Determines whether input is scalar isvector Determines whether input is vector blkdiag Constructs block diagonal matrix from input arguments circshift Shifts array circularly ctranspose Complex conjugate transpose diag Diagonal matrices and diagonals of matrix flipdim Flips array along specified dimension fliplr Flips matrix from left to right flipud Flips matrix up to down ipermute Inverses permute dimensions of N-D array permute Rearranges dimensions of N-D array repmat Replicates and tile array reshape Reshapes array rot90 Rotates matrix 90 degrees shiftdim Shifts dimensions issorted Determines whether set elements are in sorted order sort Sorts array elements in ascending or descending order sortrows Sorts rows in ascending order squeeze Removes singleton dimensions transpose Transpose vectorize Vectorizes expression Examples The following examples illustrate some of the functions mentioned above. Length, Dimension and Number of elements − Create a script file and type the following code into it − Live Demo x = [7.1, 3.4, 7.2, 28/4, 3.6, 17, 9.4, 8.9]; length(x) % length of x vector y = rand(3, 4, 5, 2); ndims(y) % no of dimensions in array y s = [”Zara”, ”Nuha”, ”Shamim”, ”Riz”, ”Shadab”]; numel(s) % no of elements in
MATLAB – M-Files
MATLAB – M-Files ”; Previous Next So far, we have used MATLAB environment as a calculator. However, MATLAB is also a powerful programming language, as well as an interactive computational environment. In previous chapters, you have learned how to enter commands from the MATLAB command prompt. MATLAB also allows you to write series of commands into a file and execute the file as complete unit, like writing a function and calling it. The M Files MATLAB allows writing two kinds of program files − Scripts − script files are program files with .m extension. In these files, you write series of commands, which you want to execute together. Scripts do not accept inputs and do not return any outputs. They operate on data in the workspace. Functions − functions files are also program files with .m extension. Functions can accept inputs and return outputs. Internal variables are local to the function. You can use the MATLAB editor or any other text editor to create your .mfiles. In this section, we will discuss the script files. A script file contains multiple sequential lines of MATLAB commands and function calls. You can run a script by typing its name at the command line. Creating and Running Script File To create scripts files, you need to use a text editor. You can open the MATLAB editor in two ways − Using the command prompt Using the IDE If you are using the command prompt, type edit in the command prompt. This will open the editor. You can directly type edit and then the filename (with .m extension) edit Or edit <filename> The above command will create the file in default MATLAB directory. If you want to store all program files in a specific folder, then you will have to provide the entire path. Let us create a folder named progs. Type the following commands at the command prompt (>>) − mkdir progs % create directory progs under default directory chdir progs % changing the current directory to progs edit prog1.m % creating an m file named prog1.m If you are creating the file for first time, MATLAB prompts you to confirm it. Click Yes. Alternatively, if you are using the IDE, choose NEW -> Script. This also opens the editor and creates a file named Untitled. You can name and save the file after typing the code. Type the following code in the editor − Live Demo NoOfStudents = 6000; TeachingStaff = 150; NonTeachingStaff = 20; Total = NoOfStudents + TeachingStaff … + NonTeachingStaff; disp(Total); After creating and saving the file, you can run it in two ways − Clicking the Run button on the editor window or Just typing the filename (without extension) in the command prompt: >> prog1 The command window prompt displays the result − 6170 Example Create a script file, and type the following code − Live Demo a = 5; b = 7; c = a + b d = c + sin(b) e = 5 * d f = exp(-d) When the above code is compiled and executed, it produces the following result − c = 12 d = 12.657 e = 63.285 f = 3.1852e-06 Print Page Previous Next Advertisements ”;
MATLAB – Data Types
MATLAB – Data Types ”; Previous Next MATLAB does not require any type declaration or dimension statements. Whenever MATLAB encounters a new variable name, it creates the variable and allocates appropriate memory space. If the variable already exists, then MATLAB replaces the original content with new content and allocates new storage space, where necessary. For example, Total = 42 The above statement creates a 1-by-1 matrix named ”Total” and stores the value 42 in it. Data Types Available in MATLAB MATLAB provides 15 fundamental data types. Every data type stores data that is in the form of a matrix or array. The size of this matrix or array is a minimum of 0-by-0 and this can grow up to a matrix or array of any size. The following table shows the most commonly used data types in MATLAB − Sr.No. Data Type & Description 1 int8 8-bit signed integer 2 uint8 8-bit unsigned integer 3 int16 16-bit signed integer 4 uint16 16-bit unsigned integer 5 int32 32-bit signed integer 6 uint32 32-bit unsigned integer 7 int64 64-bit signed integer 8 uint64 64-bit unsigned integer 9 single single precision numerical data 10 double double precision numerical data 11 logical logical values of 1 or 0, represent true and false respectively 12 char character data (strings are stored as vector of characters) 13 cell array array of indexed cells, each capable of storing an array of a different dimension and data type 14 structure C-like structures, each structure having named fields capable of storing an array of a different dimension and data type 15 function handle pointer to a function 16 user classes objects constructed from a user-defined class 17 java classes objects constructed from a Java class Example Create a script file with the following code − Live Demo str = ”Hello World!” n = 2345 d = double(n) un = uint32(789.50) rn = 5678.92347 c = int32(rn) When the above code is compiled and executed, it produces the following result − str = Hello World! n = 2345 d = 2345 un = 790 rn = 5678.9 c = 5679 Data Type Conversion MATLAB provides various functions for converting, a value from one data type to another. The following table shows the data type conversion functions − Function Purpose char Convert to character array (string) int2str Convert integer data to string mat2str Convert matrix to string num2str Convert number to string str2double Convert string to double-precision value str2num Convert string to number native2unicode Convert numeric bytes to Unicode characters unicode2native Convert Unicode characters to numeric bytes base2dec Convert base N number string to decimal number bin2dec Convert binary number string to decimal number dec2base Convert decimal to base N number in string dec2bin Convert decimal to binary number in string dec2hex Convert decimal to hexadecimal number in string hex2dec Convert hexadecimal number string to decimal number hex2num Convert hexadecimal number string to double-precision number num2hex Convert singles and doubles to IEEE hexadecimal strings cell2mat Convert cell array to numeric array cell2struct Convert cell array to structure array cellstr Create cell array of strings from character array mat2cell Convert array to cell array with potentially different sized cells num2cell Convert array to cell array with consistently sized cells struct2cell Convert structure to cell array Determination of Data Types MATLAB provides various functions for identifying data type of a variable. Following table provides the functions for determining the data type of a variable − Function Purpose is Detect state isa Determine if input is object of specified class iscell Determine whether input is cell array iscellstr Determine whether input is cell array of strings ischar Determine whether item is character array isfield Determine whether input is structure array field isfloat Determine if input is floating-point array ishghandle True for Handle Graphics object handles isinteger Determine if input is integer array isjava Determine if input is Java object islogical Determine if input is logical array isnumeric Determine if input is numeric array isobject Determine if input is MATLAB object isreal Check if input is real array isscalar Determine whether input is scalar isstr Determine whether input is character array isstruct Determine whether input is structure array isvector Determine whether input is vector class Determine class of object validateattributes Check validity of array whos List variables in workspace, with sizes and types Example Create a script file with the following code − Live Demo x = 3 isinteger(x) isfloat(x) isvector(x) isscalar(x) isnumeric(x) x = 23.54 isinteger(x) isfloat(x) isvector(x) isscalar(x) isnumeric(x) x = [1 2 3] isinteger(x) isfloat(x) isvector(x) isscalar(x) x = ”Hello” isinteger(x) isfloat(x) isvector(x) isscalar(x) isnumeric(x) When you run the file, it produces the following result − x = 3 ans = 0 ans = 1 ans = 1 ans = 1 ans = 1 x = 23.540 ans = 0 ans = 1 ans = 1 ans = 1 ans = 1 x = 1 2 3 ans = 0 ans = 1 ans = 1 ans = 0 x = Hello ans = 0 ans = 0 ans = 1 ans = 0 ans = 0 Print Page Previous Next Advertisements ”;
MATLAB – Useful Resources
MATLAB – Useful Resources ”; Previous Next The following resources contain additional information on MATLAB. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Data Preprocessing for Machine Learning using MATLAB 31 Lectures 4 hours Nouman Azam More Detail Complete MATLAB Course: Go from Beginner to Expert Best Seller 128 Lectures 12 hours Nouman Azam More Detail Image Processing Toolbox in MATLAB 18 Lectures 3 hours Sanjeev More Detail Matlab – The Complete Course Best Seller 38 Lectures 5 hours TELCOMA Global More Detail Backpropagation Learning Method in Matlab 18 Lectures 3 hours Phinite Academy More Detail Wheel Model – PID Controller in MATLAB/Simulink 10 Lectures 1.5 hours Phinite Academy More Detail Print Page Previous Next Advertisements ”;
MATLAB – Home
MATLAB Tutorial PDF Version Quick Guide Resources Job Search Discussion MATLAB is a programming language developed by MathWorks. It started out as a matrix programming language where linear algebra programming was simple. It can be run both under interactive sessions and as a batch job. This tutorial gives you aggressively a gentle introduction of MATLAB programming language. It is designed to give students fluency in MATLAB programming language. Problem-based MATLAB examples have been given in simple and easy way to make your learning fast and effective. Audience This tutorial has been prepared for the beginners to help them understand basic to advanced functionality of MATLAB. After completing this tutorial you will find yourself at a moderate level of expertise in using MATLAB from where you can take yourself to next levels. Prerequisites We assume you have a little knowledge of any computer programming and understand concepts like variables, constants, expression, statements, etc. If you have done programming in any other high-level programming language like C, C++ or Java, then it will be very much beneficial and learning MATLAB will be like a fun for you. Print Page Previous Next Advertisements ”;
MATLAB – Commands
MATLAB – Commands ”; Previous Next MATLAB is an interactive program for numerical computation and data visualization. You can enter a command by typing it at the MATLAB prompt ”>>” on the Command Window. In this section, we will provide lists of commonly used general MATLAB commands. Commands for Managing a Session MATLAB provides various commands for managing a session. The following table provides all such commands − Command Purpose clc Clears command window. clear Removes variables from memory. exist Checks for existence of file or variable. global Declares variables to be global. help Searches for a help topic. lookfor Searches help entries for a keyword. quit Stops MATLAB. who Lists current variables. whos Lists current variables (long display). Commands for Working with the System MATLAB provides various useful commands for working with the system, like saving the current work in the workspace as a file and loading the file later. It also provides various commands for other system-related activities like, displaying date, listing files in the directory, displaying current directory, etc. The following table displays some commonly used system-related commands − Command Purpose cd Changes current directory. date Displays current date. delete Deletes a file. diary Switches on/off diary file recording. dir Lists all files in current directory. load Loads workspace variables from a file. path Displays search path. pwd Displays current directory. save Saves workspace variables in a file. type Displays contents of a file. what Lists all MATLAB files in the current directory. wklread Reads .wk1 spreadsheet file. Input and Output Commands MATLAB provides the following input and output related commands − Command Purpose disp Displays contents of an array or string. fscanf Read formatted data from a file. format Controls screen-display format. fprintf Performs formatted writes to screen or file. input Displays prompts and waits for input. ; Suppresses screen printing. The fscanf and fprintf commands behave like C scanf and printf functions. They support the following format codes − Format Code Purpose %s Format as a string. %d Format as an integer. %f Format as a floating point value. %e Format as a floating point value in scientific notation. %g Format in the most compact form: %f or %e. n Insert a new line in the output string. t Insert a tab in the output string. The format function has the following forms used for numeric display − Format Function Display up to format short Four decimal digits (default). format long 16 decimal digits. format short e Five digits plus exponent. format long e 16 digits plus exponents. format bank Two decimal digits. format + Positive, negative, or zero. format rat Rational approximation. format compact Suppresses some line feeds. format loose Resets to less compact display mode. Vector, Matrix and Array Commands The following table shows various commands used for working with arrays, matrices and vectors − Command Purpose cat Concatenates arrays. find Finds indices of nonzero elements. length Computes number of elements. linspace Creates regularly spaced vector. logspace Creates logarithmically spaced vector. max Returns largest element. min Returns smallest element. prod Product of each column. reshape Changes size. size Computes array size. sort Sorts each column. sum Sums each column. eye Creates an identity matrix. ones Creates an array of ones. zeros Creates an array of zeros. cross Computes matrix cross products. dot Computes matrix dot products. det Computes determinant of an array. inv Computes inverse of a matrix. pinv Computes pseudoinverse of a matrix. rank Computes rank of a matrix. rref Computes reduced row echelon form. cell Creates cell array. celldisp Displays cell array. cellplot Displays graphical representation of cell array. num2cell Converts numeric array to cell array. deal Matches input and output lists. iscell Identifies cell array. Plotting Commands MATLAB provides numerous commands for plotting graphs. The following table shows some of the commonly used commands for plotting − Command Purpose axis Sets axis limits. fplot Intelligent plotting of functions. grid Displays gridlines. plot Generates xy plot. print Prints plot or saves plot to a file. title Puts text at top of plot. xlabel Adds text label to x-axis. ylabel Adds text label to y-axis. axes Creates axes objects. close Closes the current plot. close all Closes all plots. figure Opens a new figure window. gtext Enables label placement by mouse. hold Freezes current plot. legend Legend placement by mouse. refresh Redraws current figure window. set Specifies properties of objects such as axes. subplot Creates plots in subwindows. text Places string in figure. bar Creates bar chart. loglog Creates log-log plot. polar Creates polar plot. semilogx Creates semilog plot. (logarithmic abscissa). semilogy Creates semilog plot. (logarithmic ordinate). stairs Creates stairs plot. stem Creates stem plot. Print Page Previous Next Advertisements ”;
MATLAB – Colon Notation
MATLAB – Colon Notation ”; Previous Next The colon(:) is one of the most useful operator in MATLAB. It is used to create vectors, subscript arrays, and specify for iterations. If you want to create a row vector, containing integers from 1 to 10, you write − Live Demo 1:10 MATLAB executes the statement and returns a row vector containing the integers from 1 to 10 − ans = 1 2 3 4 5 6 7 8 9 10 If you want to specify an increment value other than one, for example − Live Demo 100: -5: 50 MATLAB executes the statement and returns the following result − ans = 100 95 90 85 80 75 70 65 60 55 50 Let us take another example − Live Demo 0:pi/8:pi MATLAB executes the statement and returns the following result − ans = Columns 1 through 7 0 0.3927 0.7854 1.1781 1.5708 1.9635 2.3562 Columns 8 through 9 2.7489 3.1416 You can use the colon operator to create a vector of indices to select rows, columns or elements of arrays. The following table describes its use for this purpose (let us have a matrix A) − Format Purpose A(:,j) is the jth column of A. A(i,:) is the ith row of A. A(:,:) is the equivalent two-dimensional array. For matrices this is the same as A. A(j:k) is A(j), A(j+1),…,A(k). A(:,j:k) is A(:,j), A(:,j+1),…,A(:,k). A(:,:,k) is the kth page of three-dimensional array A. A(i,j,k,:) is a vector in four-dimensional array A. The vector includes A(i,j,k,1), A(i,j,k,2), A(i,j,k,3), and so on. A(:) is all the elements of A, regarded as a single column. On the left side of an assignment statement, A(:) fills A, preserving its shape from before. In this case, the right side must contain the same number of elements as A. Example Create a script file and type the following code in it − Live Demo A = [1 2 3 4; 4 5 6 7; 7 8 9 10] A(:,2) % second column of A A(:,2:3) % second and third column of A A(2:3,2:3) % second and third rows and second and third columns When you run the file, it displays the following result − A = 1 2 3 4 4 5 6 7 7 8 9 10 ans = 2 5 8 ans = 2 3 5 6 8 9 ans = 5 6 8 9 Print Page Previous Next Advertisements ”;