Programming in Mathematics. Mili I. Shah

Similar documents
Matlab Programming Arrays and Scripts 1 2

Matlab Programming Introduction 1 2

Starting Matlab. MATLAB Laboratory 09/09/10 Lecture. Command Window. Drives/Directories. Go to.

Introduction to MATLAB

Introduction to Engineering gii

Introduction to MatLab. Introduction to MatLab K. Craig 1

Quick MATLAB Syntax Guide

A Guide to Using Some Basic MATLAB Functions

12 whereas if I terminate the expression with a semicolon, the printed output is suppressed.

PART 1 PROGRAMMING WITH MATHLAB

Lab of COMP 406. MATLAB: Quick Start. Lab tutor : Gene Yu Zhao Mailbox: or Lab 1: 11th Sep, 2013

MATLAB Tutorial. Mohammad Motamed 1. August 28, generates a 3 3 matrix.

MATLAB Introduction to MATLAB Programming

Importing and Exporting Data

MATLAB Tutorial EE351M DSP. Created: Thursday Jan 25, 2007 Rayyan Jaber. Modified by: Kitaek Bae. Outline

Chapter 1 Introduction to MATLAB

To start using Matlab, you only need be concerned with the command window for now.

1 Introduction to Matlab

LAB 1 General MATLAB Information 1

PROGRAMMING WITH MATLAB DR. AHMET AKBULUT

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.

INTRODUCTION TO MATLAB

Introduction to MATLAB

Introduction to MATLAB Programming. Chapter 3. Linguaggio Programmazione Matlab-Simulink (2017/2018)

MATLAB Basics EE107: COMMUNICATION SYSTEMS HUSSAIN ELKOTBY

Introduction to MATLAB. Computational Probability and Statistics CIS 2033 Section 003

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline (Cont d) MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An

Introduction to Matlab

What is MATLAB? What is MATLAB? Programming Environment MATLAB PROGRAMMING. Stands for MATrix LABoratory. A programming environment

Prof. Manoochehr Shirzaei. RaTlab.asu.edu

This is a basic tutorial for the MATLAB program which is a high-performance language for technical computing for platforms:

Outline. CSE 1570 Interacting with MATLAB. Outline. Starting MATLAB. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.

Introduction to MATLAB

Introduction to MATLAB for Numerical Analysis and Mathematical Modeling. Selis Önel, PhD

Using the fprintf command to save output to a file.

MATLAB Tutorial. Digital Signal Processing. Course Details. Topics. MATLAB Environment. Introduction. Digital Signal Processing (DSP)

Finding, Starting and Using Matlab

Programming 1. Script files. help cd Example:

General MATLAB Information 1

QUICK INTRODUCTION TO MATLAB PART I

Introduction to Matlab

Consider this m file that creates a file that you can load data into called rain.txt

AMS 27L LAB #2 Winter 2009

Lecturer: Keyvan Dehmamy

An Introductory Tutorial on Matlab

Part V Appendices c Copyright, Todd Young and Martin Mohlenkamp, Department of Mathematics, Ohio University, 2017

MATLAB Lesson I. Chiara Lelli. October 2, Politecnico di Milano

A very brief Matlab introduction

MATLAB BASICS. < Any system: Enter quit at Matlab prompt < PC/Windows: Close command window < To interrupt execution: Enter Ctrl-c.

Dr Richard Greenaway

MATLAB Basics. Configure a MATLAB Package 6/7/2017. Stanley Liang, PhD York University. Get a MATLAB Student License on Matworks

Introduction to Matlab

A QUICK INTRODUCTION TO MATLAB

Introduction to Matlab. By: Dr. Maher O. EL-Ghossain

A QUICK INTRODUCTION TO MATLAB. Intro to matlab getting started

MATH (CRN 13695) Lab 1: Basics for Linear Algebra and Matlab

LabVIEW MathScript Quick Reference

Introduction To MATLAB Introduction to Programming GENG 200

Variable Definition and Statement Suppression You can create your own variables, and assign them values using = >> a = a = 3.

Chapter 2 (Part 2) MATLAB Basics. dr.dcd.h CS 101 /SJC 5th Edition 1

Math 375 Natalia Vladimirova (many ideas, examples, and excersises are borrowed from Profs. Monika Nitsche, Richard Allen, and Stephen Lau)

Getting Started with MATLAB

Sharp EL-9900 Graphing Calculator

Chapter 2. MATLAB Basis

Lab 1 Intro to MATLAB and FreeMat

Starting MATLAB To logon onto a Temple workstation at the Tech Center, follow the directions below.

Dr Richard Greenaway

Welcome to EGR 106 Foundations of Engineering II

Introduction to Computer Programming with MATLAB Matlab Fundamentals. Selis Önel, PhD

Matlab Tutorial 1: Working with variables, arrays, and plotting

Introduction to. The Help System. Variable and Memory Management. Matrices Generation. Interactive Calculations. Vectors and Matrices

EGR 111 Introduction to MATLAB

Interactive Computing with Matlab. Gerald W. Recktenwald Department of Mechanical Engineering Portland State University

Some elements for Matlab programming

CDA6530: Performance Models of Computers and Networks. Chapter 4: Using Matlab for Performance Analysis and Simulation

Constraint-based Metabolic Reconstructions & Analysis H. Scott Hinton. Matlab Tutorial. Lesson: Matlab Tutorial

Chapter 1 MATLAB Preliminaries

Learning from Data Introduction to Matlab

CME 192: Introduction to Matlab

A Brief Introduction to MATLAB

MATLAB Functions and Graphics

EP375 Computational Physics

A 30 Minute Introduction to Octave ENGR Engineering Mathematics Tony Richardson

Experiment 1: Introduction to MATLAB I. Introduction. 1.1 Objectives and Expectations: 1.2 What is MATLAB?

ME 121 MATLAB Lesson 01 Introduction to MATLAB

Matrix Manipula;on with MatLab

Laboratory 1 Octave Tutorial

CDA5530: Performance Models of Computers and Networks. Chapter 8: Using Matlab for Performance Analysis and Simulation

MATLAB NOTES. Matlab designed for numerical computing. Strongly oriented towards use of arrays, one and two dimensional.

Teaching Manual Math 2131

STAT/MATH 395 A - PROBABILITY II UW Winter Quarter Matlab Tutorial

Introduction to Octave/Matlab. Deployment of Telecommunication Infrastructures

Mathworks (company that releases Matlab ) documentation website is:

13-Writing Data text: Chapter ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie

Chapter 11 Input/Output (I/O) Functions

A/D Converter. Sampling. Figure 1.1: Block Diagram of a DSP System

MATLAB - Lecture # 4

Basic MATLAB Tutorial

Introduction to MATLAB LAB 1

PC-MATLAB PRIMER. This is intended as a guided tour through PCMATLAB. Type as you go and watch what happens.

Transcription:

Programming in Mathematics Mili I. Shah

Starting Matlab Go to http://www.loyola.edu/moresoftware/ and login with your Loyola name and password... Matlab has eight main windows: Command Window Figure Window Editor Window Help Window Launch Pad Window Command History Window Workspace Window Current Directory Window Main window, enter variables, runs programs Contains output from graphic commands Creates and debugs script and function files Provides help information Provides access to tools, demos, and documentation Logs commands entered in the Command Window Provides information about the variables that are used Shows the files in the current directory

Command Window To type a command the cursor must be placed next to the command prompt (>>). Press Enter for the command to be executed. Multiple commands can be typed by typing a comma (,) between them. A semicolon (;) at the end of a command suppresses the screen output. Upper and lower case characters are not equivalent. The up and down arrow keys can be used to scroll through previous commands. Also an old command can be recalled by typing the first few characters followed by the up arrow. Type help topic to access online help on the command, function, or symbol topic. Type clc to clear the screen Type exit or quit to quit Matlab.

Built-In Functions >> sqrt(4) ans = 2 >> pi ans = 3.1416 sqrt(x) Square root exp(x) Exponential (e x ) abs(x) Absolute value log(x) Natural logarithm sin(x) Sine of x cos(x) Cosine of x tan(x) Tangent of x cot(x) Cotangent of x pi π

Defining Scalar Variables Variable = Numerical value or computable expression = is the assignment operator which assigns a value to a variable Left-hand side can include only one variable name Right-hand side can be a number or an expression made up of numbers and/or variables previously assigned numerical values Variables must begin with a letter Press Enter to make the assignment ans is the value of the last expression that is not assigned Remember: Use semicolon (;) to suppress screen output Multiple commands can be typed by typing a comma (,) between them.

Defining Scalar Variables Example: Assign the number 3 to variable a and 4 to variable b. Print out a 2 + b 2 and assign the solution to the variable c. >> a=3; b=4; c = sqrt(a 2+b 2) c = 5 Example: Verify cos 2 x tan x + sin x = 2 2 tan x by calculating each side of the equation for x = π/5. >> x = pi/5; >> LHS = cos(x/2) 2, RHS = (tan(x)+sin(x))/(2*tan(x)) LHS = 0.9045 RHS = 0.9045

Arrays Arrays Used to store and manipulate numbers Arranged in rows or columns One-Dimensional Array (Vector) Represents point in n-dimensional space Ex: (x, y) in 2D and (x, y, z) in 3D Row Vector (Use space or comma between numbers) >> x = [1 2 3] x = 1 2 3 Column Vector (Use semicolon between numbers) >> x = [1; 2; 3] x = 1 2 3

Arrays Constant Spaced Vectors: From m spaced by q to n variable = [m : q : n] >> x = [1:2:7] x = 1 3 5 7 From m to n with q elements variable = linspace(m,n,q) >> x = linspace(0,1,5) x = 0 0.2500 0.5000 0.7500 1.0000

Arrays Two-Dimensional Array (Matrix) Can store information like a table Solve systems of equations such as 2x + 3y + z = 4 x 5y + 3z = 3 4x 2y + 3z = 2 variable = [1st row; 2nd row;... ; last row] >>x = [ 2 3 1; 1-5 3; 4-2 3] x = 2 3 1 1 5 3 4 2 3

Addressing Elements Vector: ve(k) picks the kth element of ve ve(m:n) picks the mth through nth elements of ve >> ve = [1 5 2 6 8 7] ve = 1 5 2 6 8 7 >> ve(5) ans = 8 >> ve(2:4) ans = 5 2 6

Addressing Elements Matrix: mat(m,n) picks the (m, n)th element of mat mat(m:n,p:q) picks the (m : n) (p : q) submatrix of mat >> mat = [1 4 2 3; 3 6 9 2;1 4 9 7; 2 5 1 8] mat = 1 4 2 3 3 6 9 2 1 4 9 7 2 5 1 8 >> mat(2,3) ans = 9 >> mat(2:4, 1:3) 3 6 9 ans = 1 4 9 2 5 1

Adding Elements Can add elements by using the variable within vector/matrix Must be of appropriate size >> mat = [1 4 2 3; 3 6 9 2;1 4 9 7] mat = 1 4 2 3 3 6 9 2 1 4 9 7 >> [mat; 2 5 1 8] ans = 1 4 2 3 3 6 9 2 1 4 9 7 2 5 1 8

Deleting Elements Delete elements by assigning nothing to these elements >> ve = [1 5 2 6 8 7] ve = 1 5 2 6 8 7 >> ve(2:4) = [ ] ve = 1 8 7 >> mat = [1 4 2 3; 3 6 9 2;1 4 9 7] mat = 1 4 2 3 3 6 9 2 1 4 9 7 >> mat(2:3,:) = [ ] mat = 1 4 2 3

Helpful Tips for Arrays length(a) size(a) reshape(a,m,n) Returns number of elements in the vector A Returns size of matrix A Rearranges A to have m rows and n columns (arranged columnwise)

Matrix Operations Matrix operations can be performed by using (+,-,*,/, ) >> A = [1 4 2; 1 6 3; 1 3 2] A = 1 4 2 1 6 3 1 3 2 >> B = [1 2; 1 5; 3 6] B = 1 2 1 5 3 6 >> A*B ans = 11 34 16 50 10 29 >> B*A?

Systems of Equations Can solve systems of equations with inv or the backslash (\) >> A = [1 4 2; 1 6 3; 1 3 2] A = 1 4 2 1 6 3 1 3 2 >> b = [1; 1; 3] b = 1 1 3 >> inv(a)*b; >> A\b; See the answer for both is [1, 2, 4] T

Element-wise operations Element-wise matrix operations can be performed using (.*,./,. ) >> A = [1 4 3; 2 5 6] A = 1 4 3 2 5 6 >> B = [4 6 3; 7 3 5] B = 4 6 3 7 3 5 >> A.*B ans = 4 24 9 14 15 30

Random Arrays Can create random matrices using the following commands rand: Generates a single random number between 0 and 1 rand(1,n): Generates an n element row vector of random numbers between 0 and 1 rand(n): Generates an n n matrix with random numbers between 0 and 1 rand(m,n): Generates an m n matrix with random numbers between 0 and 1 randn: Generates normally distributed numbers with mean 0 and standard deviation 1 (inputs same as rand) randperm(n): Generates a row vector with n elements that are random perturbations of integers 1 through n

2D Plots Many different type of 2D plots plot: Basic 2D plot (x-y plane) loglog: Plot with logarithmically scaled axes semilogx: Plot with logarithmically scaled x-axis semilogy: Plot with logarithmically scaled y-axis bar: Bar graph hist: Histogram polar: Polar graph

Basic Plots Basic connect-the-dots command plot(x,y,string) >> x = linspace(-2,2); >> y = x. 2; >> plot(x,y) Now for a red curve with the markers as stars >> plot(x,y, r* ) For a full list of options type help plot loglog is the same as plot except the axes are logarithmic semilogx is the same as plot except the x-axis is logarithmic semilogy is the same as plot except the y-axis is logarithmic hold on Holds the graph so you can add more xlabel,ylabel,title,legend Labels for the graph axis auto, axis equal, axis square, axis tight axis([xmin xmax ymin ymax])

(Not so) Basic Plots % This produces one of those killer spirographs % Adapted from: % http://www.starchamber.com/paracelsus/matlab/ r1 = rand; r2 = rand; r3 = rand; a1= 0:0.15:314; a2 = a1 * r1/r2; x = (r1 - r2) * cos(a1) - cos(a2) * r3; y = (r1 - r2) * sin(a1) - sin(a2) * r3; plot(x,y) Try axis equal, axis square, grid on, axis off, hold

Scripts A script file is a sequence of commands also called a program. The output is displayed in the Command Window A script file is convenient because it can be edited and executed many times Script files can be typed and edited in any text editor and then pasted into the Matlab editor Also called an m-file because the extension.m is used

Variables Global variables: variables assigned in the Command Window and/or script file (later learn about functions that do not use these global variables) Input variables: Assign within the script Assign within the Command Window Assign within the Command Window using a prompt >> var = input( Enter a value ) input prompts user to enter a value that is assigned to var

Script Output: disp disp: Displays output on the screen disp(name of variable) or disp( text as string ) >> A = [1 4 3; 2 5 6]; >> disp(a) 1 4 3 2 5 6 >> disp( Matlab is GREAT ); Matlab is GREAT Note: disp( ) displays an empty line Note: If printing a table, spaces may have to be added for tables to line up

Script Output: fprintf in Command Window fprint: Displays output on the screen or saves output to file >> fprintf( Matlab is GREAT ); Matlab is GREAT>> fprintf( text typed in as a string ) Note: New line is not created. Use \n for a new line Note: Use \t for a horizontal tab Can be used to display a mix of text and numerical data fprintf( text %-5.2f additional text %-5.2f, var1,var2) Formatting numerical data: %Flag Precision(1 st ).Precision(2 nd ) Conversion Flag: (-) Left justifies, (+) Prints sign, (0) Adds zeros if short Precision: (1 st ) is field width, (2 nd ) is # of digits rt of decimal Conversion: (e) lower exp, (E) upper exp, (f) fixed, (i) integer

Script Output: fprintf in Command Window Example: % This script prints out the surface area and volume % of a cylinder with a given radius and height radius = 5; height = 2; surfarea = 2*pi*radius 2+ 2*pi*radius*height; vol = pi*radius 2*height; fprintf( For a cylinder with radius %i and height %e, the surface area is %5.2f and the volume is %5.3f, radius, height, surfarea, vol)

Script Output: fprintf to file Three Steps 1 Opening a file with fopen fid = fopen( filename, permission ) permission: (r) reading, (w) writing, (a) appending 2 Writing output to open file with fprintf fprintf(fid, text ) 3 Closing the file with fclose Tips Saved in current directory fclose(fid) Can write to several files using different fid, e.g. fid1, fid2 Is vectorized the command repeats itself until all elements are displayed (column-wise)

Script Output: fprintf to file Example: % This script creates a chart of inches to centimeters inches = [1:10]; centim = 2.54*inches; % Creates table to take care of vectorization TBL = [inches;centim]; fid = fopen( in2cm.txt, w ); fprintf(fid, Inches to Centimeters Table\n\n ); fprintf(fid, Inches \t Centimeters\n ); fprintf(fid, %i \t \t %3.2f\n, TBL); fclose(fid);