A Quick Octave Tutorial 阮 翀

Slides:



Advertisements
Similar presentations
Introduction to MATLAB The language of Technical Computing.
Advertisements

Introduction to M ATLAB Programming Ian Brooks Institute for Climate & Atmospheric Science School of Earth & Environment
Introduction to Matlab
AMS597 Spring 2011 Hao Han April 05, Introduction to MATLAB The name MATLAB stands for MATrix LABoratory. Typical uses include:  Math and computation.
Introduction to Matlab Workshop Matthew Johnson, Economics October 17, /13/20151.
CS231A Matlab Tutorial Philip Lee Winter Overview  Goals › Introduction to Matlab › Matlab Snippets › Basic image manipulations › Helpful Matlab.
Introduction to Matlab By: Dr. Maher O. EL-Ghossain.
What is MATLAB ? MATrix LABratory –Originally, it was a front-end to FORTRAN matrix routines developed in the U. of New Mexico and Stanford –Today.
Chapter 4 MATLAB Programming Combining Loops and Logic Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Matlab tutorial course Lesson 2: Arrays and data types
MATLAB INTRO CONTROL LAB1  The Environment  The command prompt Getting Help : e.g help sin, lookfor cos Variables Vectors, Matrices, and Linear Algebra.
Martin Ellison University of Warwick and CEPR Bank of England, December 2005 Introduction to MATLAB.
Engineering Analysis ENG 3420 Fall 2009 Dan C. Marinescu Office: HEC 439 B Office hours: Tu-Th 11:00-12:00.
M ATLAB Tutorial Course 1. Contents Continued  Desktop tools  matrices  Logical &Mathematical operations  Handle Graphics  Ordinary Differential.
Nonparametric Econometrics1 Intro to Matlab for Data Analysis and Statistical Modeling.
1 M ATLAB Short Course. History of Calculator 2 3 Introduction to Matlab Matlab is short for Matrix Laboratory Matlab is also a programming language.
Introduction to MATLAB January 18, 2008 Steve Gu Reference: Eta Kappa Nu, UCLA Iota Gamma Chapter, Introduction to MATLAB,
Introduction to Matlab 1. Outline: What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators Plotting Flow Control Using of M-File Writing.
Introduction to MATLAB
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
Introduction to MATLAB. Windows in MATLAB Command Window – where you enter data, run MATLAB code, and display results Command History - displays a log.
1 Lab of COMP 406 Teaching Assistant: Pei-Yuan Zhou Contact: Lab 1: 12 Sep., 2014 Introduction of Matlab (I)
Introduction to MATLAB CBE 502 Mathematical Methods of Engineering Analysis.
MEGN 536 – Computational Biomechanics MATLAB: Getting Started Prof. Anthony J. Petrella Computational Biomechanics Group.
A Brief Introduction to Matlab Laila Guessous Dept. of Mechanical Engineering Oakland University.
Matlab Programming, part 1 M-files It is generally more convenient to program in Matlab using m-files, ascii text files containing a set of Matlab commands.
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room A, Chris Hill, Room ,
MATLAB Tutorial EE 327 Signals and Systems 1. What is MATLAB? MATLAB – Matrix Laboratory The premier number-crunching software Extremely useful for signal.
INTRODUCTION TO MATLAB LAB# 01
Matlab Basics Tutorial. Vectors Let's start off by creating something simple, like a vector. Enter each element of the vector (separated by a space) between.
What is MATLAB? MATLAB is one of a number of commercially available, sophisticated mathematical computation tools. Others include Maple Mathematica MathCad.
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
MATLAB Practice 1 Introducing MATLAB Lecture Notes on Video Search & Mining, Spring 2012 Presented by Jun Hee Yoo Biointelligence Laboratory School of.
Flow Control and Functions ● Script files ● If's and For's ● Basics of writing functions ● Checking input arguments ● Variable input arguments ● Output.
Matlab 14.html Cost: $100 Available in labs on Windows and Unix machines.
Introduction to MATLAB Session 1 Simopekka Vänskä, THL 2010.
ME6104: CAD. Module 4. ME6104: CAD. Module 4. Systems Realization Laboratory Module 4 Matlab ME 6104 – Fundamentals of Computer-Aided Design.
Introduction to Matlab. Outline:  What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators (Arithmetic, relational, logical ) Display.
Lecture 20: Choosing the Right Tool for the Job. What is MATLAB? MATLAB is one of a number of commercially available, sophisticated mathematical computation.
A Quick Tutorial on MATLAB. MATLAB MATLAB is a software package for doing numerical computation. It was originally designed for solving linear algebra.
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
(The Transpose Operator) 1 >> C=[ ; ; ] C = >> D=C' D =
Introduction to Matlab Part II 1Daniel Baur / Introduction to Matlab Part II Daniel Baur / Michael Sokolov ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften.
MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.
Digital Image Processing Lecture 6: Introduction to M- function Programming.
Digital Image Processing Introduction to M-function Programming.
Introduction to Matlab
Introduction to Matlab Electromagnetic Theory LAB by Engr. Mian Shahzad Iqbal.
INTRODUCTION TO MATLAB DAVID COOPER SUMMER Course Layout SundayMondayTuesdayWednesdayThursdayFridaySaturday 67 Intro 89 Scripts 1011 Work
INTRODUCTION TO MATLAB Dr. Hugh Blanton ENTC 4347.
Introduction to MATLAB 1.Basic functions 2.Vectors, matrices, and arithmetic 3.Flow Constructs (Loops, If, etc) 4.Create M-files 5.Plotting.
CSE 455 : Computer Vision MATLAB 101 Getting Started with MATLAB.
SCRIPTS AND FUNCTIONS DAVID COOPER SUMMER Extensions MATLAB has two main extension types.m for functions and scripts and.mat for variable save files.
Math 252: Math Modeling Eli Goldwyn Introduction to MATLAB.
Intro to Matlab Yipei Wang & Qihui Li {yipeiw,
MATLAB (Matrix Algebra laboratory), distributed by The MathWorks, is a technical computing environment for high performance numeric computation and.
What is Matlab?  “MATLAB® is a high-level language and interactive environment for numerical computation, visualization, and programming. Using MATLAB,
L – Modeling and Simulating Social Systems with MATLAB
Scripts & Functions Scripts and functions are contained in .m-files
Outline Matlab tutorial How to start and exit Matlab Matlab basics.
MATLAB DENC 2533 ECADD LAB 9.
Matlab Workshop 9/22/2018.
MATLAB: Structures and File I/O
StatLab Matlab Workshop
Matlab review Matlab is a numerical analysis system
MATH 493 Introduction to MATLAB
Use of Mathematics using Technology (Maltlab)
StatLab Workshop: Intro to Matlab for Data Analysis and Statistical Modeling 11/29/2018.
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
How to Use MATLAB A Brief Introduction.
Presentation transcript:

A Quick Octave Tutorial 阮 翀

What is Octave? A high-level language, primarily intended for numerical computations. Not a general purpose programming language! Octave is interpreted, not compiled. Optimized for matrix operations. An open source substitute of MATLAB(Matrix Laboratory) Note: MATLAB is a commercial software. Most syntax are compatible with MATLAB. Almost all MATLAB scripts can run in Octave.

Difference between Octave & Matlab Octave absorbed some C-Style/Bash-like syntax Continuous assignment. a = b = c = 1; % Octave only [a, b, c] = deal(1); % Octave & MATLAB C-style autoincrement and assignment i++; ++i; i+=1; % Octave only String delimiters: Octave: ’ or ’’, while MATLAB requires ’ Comment: Octave: % or #, while MATLAB requires % Exponentiation: Octave: ^ or **, while MATLAB requires ^

Difference between Octave & Matlab End of blocks: Octave: end or endfor, endif, …, while MATLAB requires end Hexadecimal notation: Octave: 0x7F, while MATLAB requires hex2dec(‘7F') Line Continuation: Octave: …, \, or start a new line directly if the current expression is not closed. MATLAB: … only. Logical operator NOT: NOT (for a Boolean variable): ~ or !, while MATLAB requires ~ NOT-EQUAL: ~= or !=, while MATLAB requires ~= For more details, please refer to d_MATLAB d_MATLAB

Octave GUI Current directory Workspace Command window Command history

Define variables Use semicolons(;) to suppress output. Use square bracket([]) to denote vectors/matrices. Use whitespaces or commas(,) to separate columns. Use semicolons(;) to separate rows. Use primes(’) to denote transpose. More about this later!

Predefine variables pi: … eps: Smallest incremental number NaN: Not a number, e.g. 0/0 inf: infinity realmin, realmax: The smallest/largest usable positive real number i and j: sqrt(-1) Can be shaded by user defined variables! Use clear to clear a variable. i.e. clear j

Relation Operators Less Than: < Less Than or Equal: <= Greater Than: > Greater Than or Equal: >= Equal To: == Not Equal To: ~= or != (Octave only) Element-wise comparison is used for matrices and vectors.

Logical operators And: & or && (Octave only) Or: | or || (Octave only) Not: ~ or ! (Octave only)

The help Command Ask Octave itself if you wants to know about a command. Syntax: help

The doc Command Syntax: doc help shows comments in m-files, while doc shows corresponding documents, which is more detailed.

Matrices revisited All variables are matrices, including vectors and scalars. Recall:

More on matrices Index 1-indexed Indices starts from 1. Column-major Elements are stored column by column. Either 1-dim or 2-dim index is okay.

More on matrices One more example A(:) reshape A into a vector.

More on matrices Generating sequence Syntax : : and are included may be negative may be omitted (step=1 by default) The result is a row vector

More on matrices Slicing A(idxSet1, idxSet2) e.g.: A(1:2, 3:4) A(3, 1:2) A(2:end-1, 1) A(:,3) Use end to denote the index of the last elements along some certain dimension Use colon(:) to denote all possible indices along some dimension

More on matrices Concatenation Use repmat function Use ; and, (operate matrices as if they are scalars)

More on matrices Matrix operations vs. Element-wise operations + - * and.* ^ and.^

More on matrices Matrix operations vs. Element-wise operations / and./ A/B = A * inv(B) \ and.\ A\B = inv(A) * B Note: / and \ is much faster than inv()

More on matrices Note: Operations between scalar and a matrix is performed element by element.

More on matrices The size of a matrix can be modified when running No index-out-of-bound error! Actually, the type of a variable could change!

More on matrices Built-in Matrix Manipulation Function zeros : creates an array of all zeros, Ex: x = zeros(3,2) ones : creates an array of all ones, Ex: x = ones(2) eye : creates an identity matrix, Ex: x = eye(3) rand : generates uniformly distributed random numbers in [0,1] diag : Diagonal matrices and diagonal of a matrix size : returns array dimensions length : returns length of a vector (row or column) det : Matrix determinant inv : matrix inverse eig : evaluates eigenvalues and eigenvectors svd: singular value decompostion rank : rank of a matrix find : searches for the given values in an array/matrix. norm : matrix/vector norms.

Elementary math functions abs - finds absolute value of all elements in the matrix sign - signum function sin,cos,… - Trignometric functions asin,acos… - Inverse trignometric functions exp - Exponential log,log10 - natural logarithm, logarithm (base 10) ceil,floor - round towards +infinity, -infinity respectively round - round towards nearest integer mod - modulo, the remainder of a divided by b. real,imag - real and imaginary part of a complex matrix These functions work element-wise when applied to matrices

Elementary math functions (Cont’d) sort - sort elements in ascending order and their indices min, max – minimum/maximum value of an array and their indices sum,prod - summation and product of elements mean,median – average and median of arrays std,var - standard deviation and variance Note: when applied to matrices more than one rows, these functions work column-wise unless other designated.

Elementary math functions (Cont’d) An example

Deal with multiple return values Functions are allowed to have multiple return values Use ~ as a placeholder to filter out unwanted return values Use [] to receive multiple return values (otherwise only the first one is kept)

Graphics foundation 2D Plotting

Graphics foundation 3D Plotting

Importing/Exporting data Load and save load loads all variables from a file load loads only the variable x from the file save saves all workspace variables to a binary.mat file named filename.mat save saves variables x in filename.mat Note:.mat is the internal data format in Octave For more information, try help command

Importing/Exporting data Read from/ Write to text files fopen, fscanf, fwrite, fclose Do not forget to close a file Other useful functions fread, fprintf

Importing/Exporting data Copy data from/to an excel sheet Use command xlsread and xlswrite

Control flow If clause >> if >> … >> elseif >> … >> else >> … >> end

Control flow Switch clause >> switch >> case >> … >> case >> … >> otherwise >> … >> end Unlike C, Octave doesn’t need BREAKs in each case.

Control flow For clause >> for = >> … >> end While clause >> while >> … >> end

Control flow Break & continue The same as C.

M-files M-files are Octave source codes Do not confuse with.mat file, which is used to store data (such as matrices) There are 2 types of M-files: M-script M-function

M-files M-scripts an external file that contains a sequence of Octave statements.

M-files M-scripts Side effects: Variables remain in the workspace after M-scripts is executed. Variables already existing in the workspace may be overwritten. To list variables in the workspace, use whos command

M-files M-functions accept arguments produce one or more outputs Filename should agree with function name Sub-functions are allowed No side effects: Each M-function has its own workspace, separated from the Octave base workspace.

M-files M-functions Syntax: >> function [o1, o2, …, on] = (i1, i2, …, in) >> % one line summary (optional, but recommended) >> % more detailed description (optional) >> … >> end % optional, but recommended >> % optional sub-functions go here. Use help to check your comment. When there are only one output value, the square bracket may be omitted. function o1= (i1, i2, …, in)

M-files M-functions

M-files M-functions default parameters Use nargin

M-files M-functions function handle Useful when you want to pass a function as a Use a function handle as a function!

M-files: a summary

Other useful functions bsxfun Expand matrix virtually when necessary disp/display Useful when debugging error Syntax: error(‘some prompt here!’); Print a prompt and quit

Efficient programming (important) Avoid using nested loops as far as possible Try to replace nested loops with efficient matrix manipulation, which is called vectorization. Pre-allocate your arrays when possible Use built-in functions as much as possible.

Efficient programming (Cont’d) An example: S(n) = 1^3 + 2^3 + … + n^3 Try to avoid loops, esp. nested loops. Use built-in function will be much faster.

More advice View Octave as a powerful calculator rather than an IDE Use help/doc Think in matrices/vectors: In most cases, your function should work for both scalars, vectors and matrices Spare no effort in vectorizion Nested loop could be 1000+X slower than C/C++!

The End Any questions? Thanks for your listening.