Matlab M-Files – Quick Guide

Matlab M-Files – Quick Guide ”; Previous Next Matlab M-Files – Introduction MATLAB allows you to write a series of commands into a file and execute the file as a complete unit, like writing a function and calling it. It is done using M-file. M-File also called as the script file is a series of MATLAB commands that will get executed sequentially when the file is executed. The m-file is saved with .m extension. Program Files MATLAB allows writing two kinds of program files, which are as follows − Scripts Script files are program files with .m extension. In these files, you write a 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. A script file looks as follows − Functions Function files are also program files with .m extension. Functions can accept inputs and return outputs. Internal variables are local to the function. A function file looks as follows − Let us understand how to create and run the m-file in the next chapters. Matlab M-Files – Create & Save In this chapter, we will learn how to create and save a M-file. Let us begin by understanding about creating a M-file. Create M-file To create m-file, we will make use of MATLAB IDE as shown below. Here IDE refers to an integrated development environment. Click on New Script highlighted above to open a new script file. Save M-file You will get an untitled file. Let us save the file as firstmfile.m. Click on the save button and it will open a popup, where you can enter the name of the file. Click on OK to save the file. Now, you are free to write your commands in the file below − Matlab M-Files – Run In the previous chapter, we have seen how to create and save a m-file. Now in this chapter, we will write a simple code and run the same. Following is the code which will run inside the firstmfile.m a = 5; b = 7; c = a + b d = c + sin(b) e = 5 * d f = exp(-d) This is how it will look inside MATLAB editor − Click on the Run button as highlighted above to see the result inside the command window as shown below Matlab M-Files – 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 name of the function should be thesame. Functions operate on variables within their own workspace, which is also called the local workspace. These functions separate the variables from the workspace which you access at the MATLAB command prompt. This is called the base workspace. Functions can accept more than one input arguments and may return more than one output arguments. The syntax of a function statement is as follows − function [out1,out2, …, outN] = myfun(in1,in2,in3, …, inN) Here out1, out2…outN are output variables. It can be a single variable or comma separated. The variables in1, in2, in3…inN are input variables which can be single variable or comma separated ones. The function in MATLAB starts with the keyword function as shown in the syntax. While naming your m-file, you should take care that the file name and the function name has to match. You cannot use the name of any built-in function available in MATLAB. Let us now create a simple function and save it as .m file and run it. In MATLAB, the IDE allows you to select what type of file you want to create as shown below − Click on the Function, and it will open a new file as shown below − Now you can update the output variables, the function name and the input variables in the above untitled file and save the file with the same name as the function name. The name of our function is MaxNumber() and it gives the maximum number from the input value passed. Now let us run the function to get the output. You can call the function by using MaxNumber(100,50). Matlab M-Files – Import Data In this chapter, we will understand how to import data from an existing m-file in MATLAB. Consider the m-file firstmfile.m. The contents of the file are as follows − a = 5; b = 7; c = a + b d = c + sin(b) e = 5 * d f = exp(-d) When you execute the file, the data variables are available in the workspace, as shown below − Let us clear the workspace and the command prompt. Hence, we can now import the file and also check the data available. To clear workspace, the command is clear all. The workspace is empty now. Let us clean the command window by using clc command as shown below − We have an empty command window. Now, type the m-file name as shown below. It will execute the code inside the file The workspace is loaded with all the variables that are used inside the file. You can also check the details of the variables by using the whos command as shown below − Print Page Previous Next Advertisements ”;

Matlab M-Files – Introduction

Matlab M-Files – Introduction ”; Previous Next MATLAB allows you to write a series of commands into a file and execute the file as a complete unit, like writing a function and calling it. It is done using M-file. M-File also called as the script file is a series of MATLAB commands that will get executed sequentially when the file is executed. The m-file is saved with .m extension. Program Files MATLAB allows writing two kinds of program files, which are as follows − Scripts Script files are program files with .m extension. In these files, you write a 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. A script file looks as follows − Functions Function files are also program files with .m extension. Functions can accept inputs and return outputs. Internal variables are local to the function. A function file looks as follows − Let us understand how to create and run the m-file in the next chapters. Print Page Previous Next Advertisements ”;

MATLAB – Simulink

MATLAB – Simulink ”; Previous Next Simulink is a simulation and model-based design environment for dynamic and embedded systems, integrated with MATLAB. Simulink, also developed by MathWorks, is a data flow graphical programming language tool for modelling, simulating and analyzing multi-domain dynamic systems. It is basically a graphical block diagramming tool with customizable set of block libraries. It allows you to incorporate MATLAB algorithms into models as well as export the simulation results into MATLAB for further analysis. Simulink supports − system-level design simulation automatic code generation testing and verification of embedded systems There are several other add-on products provided by MathWorks and third-party hardware and software products that are available for use with Simulink. The following list gives brief description of some of them − Stateflow allows developing state machines and flow charts. Simulink Coder allows the generation of C source code for real-time implementation of systems automatically. xPC Target together with x86-based real-time systems provide an environment to simulate and test Simulink and Stateflow models in real-time on the physical system. Embedded Coder supports specific embedded targets. HDL Coder allows to automatically generate synthesizable VHDL and Verilog. SimEvents provides a library of graphical building blocks for modelling queuing systems. Simulink is capable of systematic verification and validation of models through modelling style checking, requirements traceability and model coverage analysis. Simulink Design Verifier allows you to identify design errors and to generate test case scenarios for model checking. Using Simulink To open Simulink, type in the MATLAB work space − simulink Simulink opens with the Library Browser. The Library Browser is used for building simulation models. On the left side window pane, you will find several libraries categorized on the basis of various systems, clicking on each one will display the design blocks on the right window pane. Building Models To create a new model, click the New button on the Library Browser”s toolbar. This opens a new untitled model window. A Simulink model is a block diagram. Model elements are added by selecting the appropriate elements from the Library Browser and dragging them into the Model window. Alternately, you can copy the model elements and paste them into the model window. Examples Drag and drop items from the Simulink library to make your project. For the purpose of this example, two blocks will be used for the simulation – A Source (a signal) and a Sink (a scope). A signal generator (the source) generates an analog signal, which will then be graphically visualized by the scope(the sink). Begin by dragging the required blocks from the library to the project window. Then, connect the blocks together which can be done by dragging connectors from connection points on one block to those of another. Let us drag a ”Sine Wave” block into the model. Select ”Sinks” from the library and drag a ”Scope” block into the model. Drag a signal line from the output of the Sine Wave block to the input of the Scope block. Run the simulation by pressing the ”Run” button, keeping all parameters default (you can change them from the Simulation menu) You should get the below graph from the scope. Print Page Previous Next Advertisements ”;

MATLAB – Discussion

Discuss MATLAB ”; Previous Next 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. Print Page Previous Next Advertisements ”;

MATLAB – Quick Guide

MATLAB – Quick Guide ”; Previous Next MATLAB – Overview 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 MATLAB – Environment Setup Local Environment Setup Setting up MATLAB environment is a matter of few clicks. The installer can be downloaded from here. MathWorks provides the licensed product, a trial version and a student version as well. You need to log into the site and wait a little for their approval. After downloading the installer the software can be installed through few clicks. Understanding the MATLAB Environment MATLAB development IDE can be launched from the icon created on the desktop. The main working window in MATLAB is called the desktop. When MATLAB is started, the desktop appears in its default layout − The desktop has the following panels − Current Folder − This panel allows you to access the project folders and files. Command Window − This is the main area where commands can be entered at the command line. It is indicated by the command prompt (>>). Workspace − The workspace shows all the variables created and/or imported from files. Command History − This panel shows or return commands that are entered at the command line. Set up GNU Octave If you are willing to use Octave on your machine ( Linux, BSD, OS X or Windows ), then kindly download latest version from Download GNU Octave. You can check the given installation instructions for your machine. MATLAB – Basic Syntax MATLAB environment behaves like a super-complex calculator. You can enter commands at the >> command prompt. MATLAB is an interpreted environment. In other words, you give a command and MATLAB executes it right away. Hands on Practice Type a valid expression, for example, Live Demo 5 + 5 And press ENTER When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is − ans = 10 Let us take up few more examples − Live Demo 3 ^ 2 % 3 raised to the power of 2 When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is − ans = 9 Another example, Live Demo sin(pi /2) % sine of angle 90o When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is − ans = 1 Another example, Live Demo 7/0 % Divide by zero When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is − ans = Inf warning: division by zero Another example, Live Demo 732 * 20.3 When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is − ans = 1.4860e+04 MATLAB provides some special expressions for some mathematical symbols, like pi for π, Inf for ∞, i (and j) for √-1 etc. Nan stands for ”not a number”. Use of Semicolon (;) in MATLAB Semicolon (;) indicates end of statement. However, if you want to suppress and hide the MATLAB output for an expression, add a semicolon after the expression. For example, Live Demo x = 3; y = x + 5 When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is − y = 8 Adding Comments The percent symbol (%) is used for indicating a comment line. For example, x = 9 % assign the value 9 to x You can also write a block of comments using the block comment operators % { and % }. The MATLAB editor includes tools and context menu items to help you add, remove, or change the format of comments. Commonly used Operators and Special Characters MATLAB supports the following commonly used operators and special characters − Operator Purpose + Plus; addition operator. – Minus; subtraction operator. * Scalar and matrix multiplication operator. .* Array multiplication operator. ^ Scalar and matrix exponentiation operator. .^ Array exponentiation operator. Left-division operator. / Right-division operator. . Array left-division operator. ./ Array right-division operator. : Colon; generates regularly spaced elements and represents an entire row or column. ( ) Parentheses; encloses function arguments and array

MATLAB – Calculus

MATLAB – Calculus ”; Previous Next MATLAB provides various ways for solving problems of differential and integral calculus, solving differential equations of any degree and calculation of limits. Best of all, you can easily plot the graphs of complex functions and check maxima, minima and other stationery points on a graph by solving the original function, as well as its derivative. This chapter will deal with problems of calculus. In this chapter, we will discuss pre-calculus concepts i.e., calculating limits of functions and verifying the properties of limits. In the next chapter Differential, we will compute derivative of an expression and find the local maxima and minima on a graph. We will also discuss solving differential equations. Finally, in the Integration chapter, we will discuss integral calculus. Calculating Limits MATLAB provides the limit function for calculating limits. In its most basic form, the limit function takes expression as an argument and finds the limit of the expression as the independent variable goes to zero. For example, let us calculate the limit of a function f(x) = (x3 + 5)/(x4 + 7), as x tends to zero. syms x limit((x^3 + 5)/(x^4 + 7)) MATLAB will execute the above statement and return the following result − ans = 5/7 The limit function falls in the realm of symbolic computing; you need to use the syms function to tell MATLAB which symbolic variables you are using. You can also compute limit of a function, as the variable tends to some number other than zero. To calculate lim x->a(f(x)), we use the limit command with arguments. The first being the expression and the second is the number, that x approaches, here it is a. For example, let us calculate limit of a function f(x) = (x-3)/(x-1), as x tends to 1. limit((x – 3)/(x-1),1) MATLAB will execute the above statement and return the following result − ans = NaN Let”s take another example, limit(x^2 + 5, 3) MATLAB will execute the above statement and return the following result − ans = 14 Calculating Limits using Octave Following is Octave version of the above example using symbolic package, try to execute and compare the result − pkg load symbolic symbols x = sym(“x”); subs((x^3+5)/(x^4+7),x,0) Octave will execute the above statement and return the following result − ans = 0.7142857142857142857 Verification of Basic Properties of Limits Algebraic Limit Theorem provides some basic properties of limits. These are as follows − Let us consider two functions − f(x) = (3x + 5)/(x – 3) g(x) = x2 + 1. Let us calculate the limits of the functions as x tends to 5, of both functions and verify the basic properties of limits using these two functions and MATLAB. Example Create a script file and type the following code into it − syms x f = (3*x + 5)/(x-3); g = x^2 + 1; l1 = limit(f, 4) l2 = limit (g, 4) lAdd = limit(f + g, 4) lSub = limit(f – g, 4) lMult = limit(f*g, 4) lDiv = limit (f/g, 4) When you run the file, it displays − l1 = 17 l2 = 17 lAdd = 34 lSub = 0 lMult = 289 lDiv = 1 Verification of Basic Properties of Limits using Octave Following is Octave version of the above example using symbolic package, try to execute and compare the result − pkg load symbolic symbols x = sym(“x”); f = (3*x + 5)/(x-3); g = x^2 + 1; l1 = subs(f, x, 4) l2 = subs (g, x, 4) lAdd = subs (f+g, x, 4) lSub = subs (f-g, x, 4) lMult = subs (f*g, x, 4) lDiv = subs (f/g, x, 4) Octave will execute the above statement and return the following result − l1 = 17.0 l2 = 17.0 lAdd = 34.0 lSub = 0.0 lMult = 289.0 lDiv = 1.0 Left and Right Sided Limits When a function has a discontinuity for some particular value of the variable, the limit does not exist at that point. In other words, limits of a function f(x) has discontinuity at x = a, when the value of limit, as x approaches x from left side, does not equal the value of the limit as x approaches from right side. This leads to the concept of left-handed and right-handed limits. A left-handed limit is defined as the limit as x -> a, from the left, i.e., x approaches a, for values of x < a. A right-handed limit is defined as the limit as x -> a, from the right, i.e., x approaches a, for values of x > a. When the left-handed limit and right-handed limit are not equal, the limit does not exist. Let us consider a function − f(x) = (x – 3)/|x – 3| We will show that limx->3 f(x) does not exist. MATLAB helps us to establish this fact in two ways − By plotting the graph of the function and showing the discontinuity. By computing the limits and showing that both are different. The left-handed and right-handed limits are computed by passing the character strings ”left” and ”right” to the limit command as the last argument. Example Create a script file and type the following code into it − f = (x – 3)/abs(x-3); ezplot(f,[-1,5]) l = limit(f,x,3,”left”) r = limit(f,x,3,”right”) When you run the file, MATLAB draws the following plot After this following output is displayed − l = -1 r = 1 Print Page Previous Next Advertisements ”;

MATLAB – Matrix

MATLAB – Matrix ”; Previous Next A matrix is a two-dimensional array of numbers. In MATLAB, you create a matrix by entering elements in each row as comma or space delimited numbers and using semicolons to mark the end of each row. For example, let us create a 4-by-5 matrix a − Live Demo a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8] MATLAB will execute the above statement and return the following result − a = 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 Referencing the Elements of a Matrix To reference an element in the mth row and nth column, of a matrix mx, we write − mx(m, n); For example, to refer to the element in the 2nd row and 5th column, of the matrix a, as created in the last section, we type − Live Demo a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8]; a(2,5) MATLAB will execute the above statement and return the following result − ans = 6 To reference all the elements in the mth column we type A(:,m). Let us create a column vector v, from the elements of the 4th row of the matrix a − Live Demo a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8]; v = a(:,4) MATLAB will execute the above statement and return the following result − v = 4 5 6 7 You can also select the elements in the mth through nth columns, for this we write − a(:,m:n) Let us create a smaller matrix taking the elements from the second and third columns − Live Demo a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8]; a(:, 2:3) MATLAB will execute the above statement and return the following result − ans = 2 3 3 4 4 5 5 6 In the same way, you can create a sub-matrix taking a sub-part of a matrix. Live Demo a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8]; a(:, 2:3) MATLAB will execute the above statement and return the following result − ans = 2 3 3 4 4 5 5 6 In the same way, you can create a sub-matrix taking a sub-part of a matrix. For example, let us create a sub-matrix sa taking the inner subpart of a − 3 4 5 4 5 6 To do this, write − Live Demo a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8]; sa = a(2:3,2:4) MATLAB will execute the above statement and return the following result − sa = 3 4 5 4 5 6 Deleting a Row or a Column in a Matrix You can delete an entire row or column of a matrix by assigning an empty set of square braces [] to that row or column. Basically, [] denotes an empty array. For example, let us delete the fourth row of a − Live Demo a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8]; a( 4 , : ) = [] MATLAB will execute the above statement and return the following result − a = 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 Next, let us delete the fifth column of a − Live Demo a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8]; a(: , 5)=[] MATLAB will execute the above statement and return the following result − a = 1 2 3 4 2 3 4 5 3 4 5 6 4 5 6 7 Example In this example, let us create a 3-by-3 matrix m, then we will copy the second and third rows of this matrix twice to create a 4-by-3 matrix. Create a script file with the following code − Live Demo a = [ 1 2 3 ; 4 5 6; 7 8 9]; new_mat = a([2,3,2,3],:) When you run the file, it displays the following result − new_mat = 4 5 6 7 8 9 4 5 6 7 8 9 Matrix Operations In this section, let us discuss the following basic and commonly used matrix operations − Addition and Subtraction of Matrices Division of Matrices Scalar Operations of Matrices Transpose of a Matrix Concatenating Matrices Matrix Multiplication Determinant of a Matrix Inverse of a Matrix Print Page Previous Next Advertisements ”;

MATLAB – Operators

MATLAB – Operators ”; Previous Next An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. MATLAB is designed to operate primarily on whole matrices and arrays. Therefore, operators in MATLAB work both on scalar and non-scalar data. MATLAB allows the following types of elementary operations − Arithmetic Operators Relational Operators Logical Operators Bitwise Operations Set Operations Arithmetic Operators MATLAB allows two different types of arithmetic operations − Matrix arithmetic operations Array arithmetic operations Matrix arithmetic operations are same as defined in linear algebra. Array operations are executed element by element, both on one-dimensional and multidimensional array. The matrix operators and array operators are differentiated by the period (.) symbol. However, as the addition and subtraction operation is same for matrices and arrays, the operator is same for both cases. The following table gives brief description of the operators − Show Examples Sr.No. Operator & Description 1 + Addition or unary plus. A+B adds the values stored in variables A and B. A and B must have the same size, unless one is a scalar. A scalar can be added to a matrix of any size. 2 – Subtraction or unary minus. A-B subtracts the value of B from A. A and B must have the same size, unless one is a scalar. A scalar can be subtracted from a matrix of any size. 3 * Matrix multiplication. C = A*B is the linear algebraic product of the matrices A and B. More precisely, For non-scalar A and B, the number of columns of A must be equal to the number of rows of B. A scalar can multiply a matrix of any size. 4 .* Array multiplication. A.*B is the element-by-element product of the arrays A and B. A and B must have the same size, unless one of them is a scalar. 5 / Slash or matrix right division. B/A is roughly the same as B*inv(A). More precisely, B/A = (A”B”)”. 6 ./ Array right division. A./B is the matrix with elements A(i,j)/B(i,j). A and B must have the same size, unless one of them is a scalar. 7 Backslash or matrix left division. If A is a square matrix, AB is roughly the same as inv(A)*B, except it is computed in a different way. If A is an n-by-n matrix and B is a column vector with n components, or a matrix with several such columns, then X = AB is the solution to the equation AX = B. A warning message is displayed if A is badly scaled or nearly singular. 8 . Array left division. A.B is the matrix with elements B(i,j)/A(i,j). A and B must have the same size, unless one of them is a scalar. 9 ^ Matrix power. X^p is X to the power p, if p is a scalar. If p is an integer, the power is computed by repeated squaring. If the integer is negative, X is inverted first. For other values of p, the calculation involves eigenvalues and eigenvectors, such that if [V,D] = eig(X), then X^p = V*D.^p/V. 10 .^ Array power. A.^B is the matrix with elements A(i,j) to the B(i,j) power. A and B must have the same size, unless one of them is a scalar. 11 ” Matrix transpose. A” is the linear algebraic transpose of A. For complex matrices, this is the complex conjugate transpose. 12 .” Array transpose. A.” is the array transpose of A. For complex matrices, this does not involve conjugation. Relational Operators Relational operators can also work on both scalar and non-scalar data. Relational operators for arrays perform element-by-element comparisons between two arrays and return a logical array of the same size, with elements set to logical 1 (true) where the relation is true and elements set to logical 0 (false) where it is not. The following table shows the relational operators available in MATLAB − Show Examples Sr.No. Operator & Description 1 < Less than 2 <= Less than or equal to 3 > Greater than 4 >= Greater than or equal to 5 == Equal to 6 ~= Not equal to Logical Operators MATLAB offers two types of logical operators and functions − Element-wise − These operators operate on corresponding elements of logical arrays. Short-circuit − These operators operate on scalar and, logical expressions. Element-wise logical operators operate element-by-element on logical arrays. The symbols &, |, and ~ are the logical array operators AND, OR, and NOT. Short-circuit logical operators allow short-circuiting on logical operations. The symbols && and || are the logical short-circuit operators AND and OR. Show Examples Bitwise Operations Bitwise operators work on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows − p q p & q p | q p ^ q 0 0 0 0 0 0 1 0 1 1 1 1 1 1 0 1 0 0 1 1 Assume if A = 60; and B = 13; Now in binary format they will be as follows − A = 0011 1100 B = 0000 1101 —————– A&B = 0000 1100 A|B = 0011 1101 A^B = 0011 0001 ~A  = 1100 0011 MATLAB provides various functions for bit-wise operations like ”bitwise and”, ”bitwise or” and ”bitwise not” operations, shift operation, etc. The following table shows the commonly used bitwise operations − Show Examples Function Purpose bitand(a, b) Bit-wise AND of integers a and b bitcmp(a) Bit-wise complement of a bitget(a,pos) Get bit at specified position pos, in the integer array a bitor(a, b) Bit-wise OR of integers a and b bitset(a, pos) Set bit at specific location pos of a bitshift(a, k) Returns a shifted to the left by k bits, equivalent to multiplying by 2k. Negative values of k correspond to shifting bits right or dividing by 2|k| and rounding to the nearest integer towards negative infinite. Any overflow bits are truncated. bitxor(a, b) Bit-wise XOR of integers a and b

MATLAB – Vectors

MATLAB – Vectors ”; Previous Next A vector is a one-dimensional array of numbers. MATLAB allows creating two types of vectors − Row vectors Column vectors Row Vectors Row vectors are created by enclosing the set of elements in square brackets, using space or comma to delimit the elements. 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 Column Vectors 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 Referencing the Elements of a Vector You can reference one or more of the elements of a vector in several ways. The ith component of a vector v is referred as v(i). For example − Live Demo v = [ 1; 2; 3; 4; 5; 6]; % creating a column vector of 6 elements v(3) MATLAB will execute the above statement and return the following result − ans = 3 When you reference a vector with a colon, such as v(:), all the components of the vector are listed. Live Demo v = [ 1; 2; 3; 4; 5; 6]; % creating a column vector of 6 elements v(:) MATLAB will execute the above statement and return the following result − ans = 1 2 3 4 5 6 MATLAB allows you to select a range of elements from a vector. For example, let us create a row vector rv of 9 elements, then we will reference the elements 3 to 7 by writing rv(3:7) and create a new vector named sub_rv. Live Demo rv = [1 2 3 4 5 6 7 8 9]; sub_rv = rv(3:7) MATLAB will execute the above statement and return the following result − sub_rv = 3 4 5 6 7 Vector Operations In this section, let us discuss the following vector operations − Addition and Subtraction of Vectors Scalar Multiplication of Vectors Transpose of a Vector Appending Vectors Magnitude of a Vector Vector Dot Product Vectors with Uniformly Spaced Elements Print Page Previous Next Advertisements ”;

MATLAB – GNU Octave

MATLAB – GNU Octave Tutorial ”; Previous Next GNU Octave is a high-level programming language like MATLAB and it is mostly compatible with MATLAB. It is also used for numerical computations. Octave has the following common features with MATLAB − matrices are fundamental data type it has built-in support for complex numbers it has built-in math functions and libraries it supports user-defined functions GNU Octave is also freely redistributable software. You may redistribute it and/or modify it under the terms of the GNU General Public License (GPL) as published by the Free Software Foundation. MATLAB vs Octave Most MATLAB programs run in Octave, but some of the Octave programs may not run in MATLAB because, Octave allows some syntax that MATLAB does not. For example, MATLAB supports single quotes only, but Octave supports both single and double quotes for defining strings. If you are looking for a tutorial on Octave, then kindly go through this tutorial from beginning which covers both MATLAB as well as Octave. Compatible Examples Almost all the examples covered in this tutorial are compatible with MATLAB as well as Octave. Let”s try following example in MATLAB and Octave which produces same result without any syntax changes − This example creates a 3D surface map for the function g = xe-(x2 + y2). Create a script file and type the following code − [x,y] = meshgrid(-2:.2:2); g = x .* exp(-x.^2 – y.^2); surf(x, y, g) print -deps graph.eps When you run the file, MATLAB displays the following 3-D map − Non-compatible Examples Though all the core functionality of MATLAB is available in Octave, there are some functionality for example, Differential & Integration Calculus, which does not match exactly in both the languages. This tutorial has tried to give both type of examples where they differed in their syntax. Consider following example where MATLAB and Octave make use of different functions to get the area of a curve: f(x) = x2 cos(x) for −4 ≤ x ≤ 9. Following is MATLAB version of the code − f = x^2*cos(x); ezplot(f, [-4,9]) a = int(f, -4, 9) disp(”Area: ”), disp(double(a)); When you run the file, MATLAB plots the graph − The following result is displayed a = 8*cos(4) + 18*cos(9) + 14*sin(4) + 79*sin(9) Area: 0.3326 But to give area of the same curve in Octave, you will have to make use of symbolic package as follows − pkg load symbolic symbols x = sym(“x”); f = inline(“x^2*cos(x)”); ezplot(f, [-4,9]) print -deps graph.eps [a, ierror, nfneval] = quad(f, -4, 9); display(”Area: ”), disp(double(a)); Print Page Previous Next Advertisements ”;