Lecture 2: Advanced Programming Topics

Size: px
Start display at page:

Download "Lecture 2: Advanced Programming Topics"

Transcription

1 Lecture 2: Advanced Programming Topics Characters and Strings A character in the MATLAB software is actually an integer value converted to its Unicode character equivalent. A character string is a vector with components that are the numeric codes for the characters. The actual characters displayed depend on the character set encoding for a given font. The elements of a character or string belong to the char class. Arrays of class char can hold multiple strings, as long as each string in the array has the same length. (This is because MATLAB arrays must be rectangular.) To store an array of strings of unequal length, use a cell array. Creating a Single Character Store a single character in the MATLAB workspace by enclosing the character in single quotation marks and assigning it to a variable: >> hchar = 'h'; This creates a 1-by-1 matrix of class char. Each character occupies 2 bytes of workspace memory: The numeric value of hchar is 104: >> uint8(hchar) ans = 104 Creating a Character String Create a string by enclosing a sequence of letters in single quotation marks. MATLAB represents the five-character string shown below as a 1-by-5 vector of class char. It occupies 2 bytes of memory for each character in the string: >> str = 'Hello'; The uint8 function converts characters to their numeric values:

2 >> str_numeric = uint8(str) str_numeric = The char function converts the integer vector back to characters: >> str_alpha = char([ ]) str_alpha = Hello Creating an Array of Strings Create an array of strings in the same way that you would create a numeric array. Use the array constructor ([]), delimit each row in the array with a semicolon, and enclose each string in single quotation marks. Like numeric arrays, character arrays must be rectangular. That is, each row of the array must be the same length: >> name = ['Thomas R. Lee';... 'Sr. Developer';... 'SFTware Corp.']; String Functions: Comparisons strcmp determines if two strings are identical. strncmp determines if the first n characters of two strings are identical. strcmpi and strncmpi are the same as strcmp and strncmp, except that they ignore case. String Functions: Searching and Replacing The strrep function performs the standard search-and-replace operation. findstr returns the starting position of a substring within a longer string. The strmatch function looks through the rows of a character array or cell array of strings to find strings that begin with a given series of characters. It returns the indices of the rows that begin with these characters. Exercise

3 Write a script that does the following: 1. Prompt for the user to enter a string and save it in a variable called str. What do you have to do to make it read in a character or string? 2. Set the variable sentence to be : 'Because MATLAB is very exciting.' 3. Replace all occurences of str in the sentence with 'However,' and include another reason 'and I love food.' 4. Test it with the following: str = 'Because' Example: If the why command returns Because Damien says so., your script should return However, Damien says so and I love food. Save your script as PROBLEM1.m File I/O Matlab supports C-style file input and output and provides most of the same functionality and same syntax commands as C. The following C commands are all available for file I/O under Matlab. fprintf sprintf fopen fclose fscanf Example >>A=[ ]; >>fid=fopen( myoutput, w ); >>fprintf(fid,%g miles/hour= %g kilometers/hour\n, [A;8*A/5]); >>fclose(fid); >>fid=fopen( myoutput, r ); >>X=fscanf(fid, %g miles/hour=%g kilometers/hour ) >>Y=fscanf(fid,%g miles/hour = %g kilometers/hour,[2 inf]) >>fclose(fid); Read the help files for these functions to see all the various formatting options. Matlab also provides a more powerful function called textscan. Textscan is used to scan textfiles and has a different syntax and output than fscanf. Example >>fid=fopen( myoutput, r ); >>C=textscan(fid, %f miles/hour = %f kilometers/hour )

4 >>C{1} >>C{2} Structures and Cells We have seen vectors and matrices as well as multidimensional arrays in the previous lecture. While incredibly useful they are limited in a few key ways. None of these data types can handle mixed data and all the data must be of the same size. To overcome these problems Matlab has structures and cells. Cells are used in many built in Matlab functions, especially those that can accept an unknown number of inputs or return an unknown number of outputs. Structures and cells serve similar purposes but the key difference lies in how they are indexed. Cells are also somewhat more flexible than structures. See help datatypes for a listing of all the functions for manipulating cells and structures. A structure is a data structure that identifies each data entry with a chosen text name. They are also called records in other programming languages. You can create n-dimensional arrays of structs the same as you would create an n-dimensional array of numbers. An intuitive example of a struct is calendar entry in a schedule book. Structures are primarily of use when we can expect our data to fall into some predetermined format. There are two different ways to declare a struct. Structures Examples type 1(Direct initialization of 1-D struct arrays.) >>Datebook(1).event= Dinner with Friends ; >>Datebook(1).day=15; >>Datebook(1).month= Jan ; >>Datebook(1).year=2010; >>Datebook(1).time=1800; >>Datebook(2).event= Hockey Game ; >>Datebook(2).day=25; >>Datebook(2).month= Feb ; >>Datebook(2).year=2010; >>Datebook(2).time=1900 >>Datebook >>Datebook(2).event >>Datebook(1).day >>n=4 >>testmat(1).name= Hilbert ; >>testmat(1).mat=hilb(n);

5 >>testmat(1).eig=eig(hilb(n)); >>testmat(2).name= Pascal ; >>testmat(2).mat=pascal(n); >>testmat(2).eig=eig(pascal(n)); >>testmat >>testmat(2).name >>testmat(1).mat >>testmat(2).eig >>testmat(1).mat(1:2,1:2) Structures Examples 2(Creating structs using the struct command) >>clear testmat Datebook; >>Datebookt=struct( event,{ Dinner with Friends, Hockey Game }, day,{15,25}, month,{ Jan, Feb }, year,{2010,2010}, time,{1800,1900}); >>testmat=struct( name,{ Hilbert, Pascal }, mat,{hilb(n),pascal(n), eig,{eig(hilb(n)),eig(pascal(n))}); >>Datebook, testmat Structures Examples 3(Creating 5 by 5 arrays of empty structs using repmat) >>clear testmat Datebook; >>Datebook=repmat(struct( event,{ }, day,{0}, month,{ }, year,{0}, time,{0},5,5) >>testmat=repmat(struct( name,{ }, mat,{zeros(n)}, eig,{zeros(n,1)}),5,5) Cells are in the same spirit as structs, however the entries of a cell are not named. Cells are very useful when we wish to combine data types but do not have an expected data format. We already saw one example of how Matlab uses cells to handle an unknown number of outputs when we used the command textscan. Note that cells are enclosed by {} at declaration unlike a struct.

6 Cell Example 1 (Create a 2 by 2 cell of different types) >>C={1:3,pi; magic(2), A string } >>C{1,1} >>C{2,:} >>C{2,1}(2,2) Cell Example 2(Showing the equivalence of Cells and Structs) >>clear testmat >>testmat{1,1}= Hilbert ; >>testmat{2,1}=hilb(n); >>testmat{3,1}=eig(hilb(n)); >>testmat{1,2}= Pascal ; >>testmat{2,2}=pascal(n); >>testmat{3,2}=eig(pascal(n)); >>testmat >>celldisp(testmat) >>testmat(1,1)={ Hilbert }; >>testmat{2,1}(4,4) Cell Example 3 >>clear testmat >>testmat=cell(3,2); Matlab also has cell2struct and struct2cell for converting between structs and cells. Efficiency Writing code that is correct is only one half of programming. Code also needs to be efficient to be truly useful. While Matlab code is never going to be as fast as compiled languages such as C or C++, there are still steps one can take to improve the speed of Matlab code. tic and toc To begin profiling code for efficiency, Matlab provides the tic and toc commands. Tic and toc are used as a pair and should bracket the code block that you wish to examine. When used appropriately these commands can help determine where code spends a majority of its processing time without the need for more complex profiling tools. Vectorizing Code and Preallocating Memory Matlab has been optimized to run code on vectors and matrices. Some of the biggest speedups in Matlab, historically, have be achieved by looking for clever ways to eliminate for loops or excessive index

7 access and instead use vectors or matrices to store data and perform parallel computation. However, Matlab has greatly improved the efficiency of for loops in more modern releases, and for smaller or less complex problems, for loops can often achieve the same speed as the vectorized equivalent. Additionally, preallocating memory can greatly speed up for loops. Note that Matlab will dynamically assign memory as needed. For example, if a vector is growing within a for loop Matlab will assign memory as needed to store the vector, but this can become very slow for very large for loops. A more detailed guide to this process can be found at A Simple Contrived Example >>A=rand(100000,1);B=rand(100000,1); >>clear C; >>tic, for i=1:100000,c(i)=a(i)+b(i);end,toc >>clear C; >>C=zeros(100000,1); >>tic, for i=1:100000,c(i)=a(i)+b(i);end,toc >>clear C; >>tic,c=a+b;toc >>clear C; >>C=zeros(100000,1); >>tic,c=a+b;toc Another Contrived Example >>A = magic(100); >> B = pascal(100); >>tic, for j = 1:100 for k = 1:100; X(j,k) = sqrt(a(j,k)) * (B(j,k) - 1); end end,toc >>clear X >>tic,x = sqrt(a).*(b-1),toc;

8 Using Permutations Another common trick exploited in more advanced Matlab code is the use of permutations to reorder data. A vector that represents the desired index permutation is used to index the vector to be reordered and the output saved. One can also use these tricks to reorder the rows or columns of a matrix as will be seen in the examples. Example 1(Vectors) >> x = [ ] >>x=x([ ]) >>[s,ix]=sort(x) >>ix_inv(ix)=1:length(ix); >>s(ix_inv) Example 2(Matrices) >>A=magic(4);p=[ ]; >>I=eye(4);P=I(p,:) >>P*A >>A(p,:) >>A*P >>A(:,p) To generate a random permutation Matlab offers the command randperm >>randperm(8) Additionally Matlab offers the commands permute and ipermute that will rearrange the dimensions of a matrix according to a permutation vector. Example 3(Permuting Matrix Dimensions) >>A=rand(12,13,14); >>B=permute(A,[3 2 1]); >>size(b) >>C=ipermute(B,[3 2 1]); >>size(c) Using the Profiler Matlab offers a built in code profiler tool that will capture information about all commands and calls run by Matlab. It can be activated from either the command line or the GUI. When the profiler is activated, it will capture the runtime information and all function calls made by the code executed. Example(Using the Profiler from the Command line)

9 >>help profile >> profile on history >>magic(4); >>profile off; >>profile viewer Commenting and the Help Command It is a good idea to comment your code using brief and descriptive comments so that goal of your code is as obvious as possible. It s not necessary to comment every bit of your code, but any area that isn t obvious from the code itself should receive some amount of commenting. It is also good style to document the inputs, outputs and expected usage or behavior of your code at the top of your files. In Matlab, the help command will return any comments written into the m-file before the first line of executable code. Executable code does not include the function declaration itself. Input Checking Many runtime errors result not from the code, but from a failure to properly check the data being input to the code (This applies to all languages). It is a good idea to include input checking into any code that is intended for use by outside parties (and is of course beneficial even for personal use code). Failure to properly check inputs can result in code crashing, bizarre code behavior and even security vulnerabilities (depending on the situation). In Matlab, some principle tools for checking inputs to functions are the is* functions such as isreal or ischar(see helpwin is* for a full listing), the size and length functions, and the class command. Errors and Warnings Matlab provides the functions error and warning for returning and displaying customized error and warning messages. These will be used in the first exercise and you should read the help files. Debugging Debugging code can be an exhausting proposition. There are two types of errors that will prevent your code from running to completion: syntax errors and runtime errors. Syntax errors are generally relatively obvious problems and the m-lint (lint tools are available for a variety of languages and I can t recommend them enough) tool in the Matlab editor makes finding these errors relatively straightforward. Run-time errors are errors that occur during the execution of your code and tend to be more algorithmic in nature. For

10 instance you may miscalculate an index and thus access the wrong data or perhaps call the wrong vector when assigning output. If your code is well structured and documented it can make isolating errors a more straightforward exercise. When debugging code I tend to follow this checklist. 1. Check my input to make sure I m not entering garbage data to the code 2. Check core algorithm code sections for any obvious typos or indexing errors 3. Display the output from intermediate calculation steps. If there are several steps that would flood my display or if there is code in a loop I ll utilize pause commands to step through the code for some reduced size input. Alternatively outputs can be sent to a log file using file I/O and then read through at leisure. 4. If none of the above steps reveal any problems I ll reexamine my algorithm and code for any subtle problems or bizarre cases that could cause problems. This checklist is a bit primitive in some ways, but it tends to work relatively well in most cases and for a wide range of programming languages. More complex code with several calls to subfunctions that could be in error can become more complicated to deal with in this fashion, but thorough testing of subfunctions(and/or examining subfunction input and output) before use can help with this problem.(a good coding practice is to validate small units of code at a time. This is called Unit Testing is the software engineering realm) Additionally, there are several more powerful tools that exist for the purpose of runtime code analysis. Matlab has a built in runtime debugger that can be used to step through code and examine runtime data at set points of interest. This tool replaces step 3 in my checklist and many major programming languages have code debugging tools similar to the Matlab tool(i.e. gdb for C/C++ code). The debugger can be called from either the command line or accessed through the Matlab editor. Key commands for the command line are dbstop dbquit dbcont dbstep dbclear dbtype dbstack

11 dbup dbdown dbstatus Exercise 5 will involve working through an example debugging process using the Matlab debugger from the editor. Exercises 1) Write a function that accepts as input 2 real numbers and returns a vector containing their sum difference, product, quotient(num1/num2) and num1/sqrt(num2). (e.g., something of the form function V=myfuncname(input1,input2)) Comment the code so that help will display the inputs and outputs of the function and explain the functions behavior and usage Check the input to make sure the numbers are realvalued and scalar and return an error if they are not Display a warning if the second input is negative or zero Profile the code and save a profile report of the run. 2) Write a function that prompts the user for their name, date of birth and eye color. Store these elements in both a struct and a cell. Input can accept strings as well an numerical input and the help file shows how to do this. 3) Modify your function from 2 to also write the data to a file called name.txt. The function strcat will be useful here. 4) Read out the data stored in name.txt and display it on the screen. Read the helpfile for fscanf to find the appropriate formatting to read the string data. 5) In the Matlab helpwin search for Debugging Process and Features and work through the example problem.

Computational Methods of Scientific Programming

Computational Methods of Scientific Programming 12.010 Computational Methods of Scientific Programming Lecturers Thomas A Herring, Jim Elliot, Chris Hill, Summary of Today s class We will look at Matlab: History Getting help Variable definitions and

More information

PREPARED FOR: ME 352: MACHINE DESIGN I Fall Semester School of Mechanical Engineering Purdue University West Lafayette, Indiana

PREPARED FOR: ME 352: MACHINE DESIGN I Fall Semester School of Mechanical Engineering Purdue University West Lafayette, Indiana INTRODUCTORY TUTORIAL TO MATLAB PREPARED FOR: ME 352: MACHINE DESIGN I Fall Semester 2017 School of Mechanical Engineering Purdue University West Lafayette, Indiana 47907-2088 August 21st, 2017 Table of

More information

Matlab Basics. Paul Schrimpf. January 14, Paul Schrimpf () Matlab Basics January 14, / 24

Matlab Basics. Paul Schrimpf. January 14, Paul Schrimpf () Matlab Basics January 14, / 24 Matlab Basics Paul Schrimpf January 14, 2009 Paul Schrimpf () Matlab Basics January 14, 2009 1 / 24 Overview Goals Matlab features Program design Numerical methods Paul Schrimpf () Matlab Basics January

More information

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing SECTION 1: INTRODUCTION ENGR 112 Introduction to Engineering Computing 2 Course Overview What is Programming? 3 Programming The implementation of algorithms in a particular computer programming language

More information

MATLAB: Quick Start Econ 837

MATLAB: Quick Start Econ 837 MATLAB: Quick Start Econ 837 Introduction MATLAB is a commercial Matrix Laboratory package which operates as an interactive programming environment. It is a programming language and a computing environment

More information

Computers Programming Course 11. Iulian Năstac

Computers Programming Course 11. Iulian Năstac Computers Programming Course 11 Iulian Năstac Recap from previous course Cap. Matrices (Arrays) Matrix representation is a method used by a computer language to store matrices of different dimension in

More information

CME 192: Introduction to Matlab

CME 192: Introduction to Matlab CME 192: Introduction to Matlab Matlab Basics Brett Naul January 15, 2015 Recap Using the command window interactively Variables: Assignment, Identifier rules, Workspace, command who and whos Setting the

More information

Matlab- Command Window Operations, Scalars and Arrays

Matlab- Command Window Operations, Scalars and Arrays 1 ME313 Homework #1 Matlab- Command Window Operations, Scalars and Arrays Last Updated August 17 2012. Assignment: Read and complete the suggested commands. After completing the exercise, copy the contents

More information

String Manipulation. Chapter 7. Attaway MATLAB 4E

String Manipulation. Chapter 7. Attaway MATLAB 4E String Manipulation Chapter 7 Attaway MATLAB 4E Strings: Terminology A string in MATLAB consists of any number of characters and is contained in single quotes strings are vectors in which every element

More information

SECTION 5: STRUCTURED PROGRAMMING IN MATLAB. ENGR 112 Introduction to Engineering Computing

SECTION 5: STRUCTURED PROGRAMMING IN MATLAB. ENGR 112 Introduction to Engineering Computing SECTION 5: STRUCTURED PROGRAMMING IN MATLAB ENGR 112 Introduction to Engineering Computing 2 Conditional Statements if statements if else statements Logical and relational operators switch case statements

More information

Chapter 9. Above: An early computer input/output device on the IBM 7030 (STRETCH)

Chapter 9. Above: An early computer input/output device on the IBM 7030 (STRETCH) Chapter 9 Above: An early computer input/output device on the IBM 7030 (STRETCH) http://computer-history.info/page4.dir/pages/ibm.7030.stretch.dir/ Io One of the moon s of Jupiter (A Galilean satellite)

More information

Worksheet 6. Input and Output

Worksheet 6. Input and Output Worksheet 6. Input and Output Most programs (except those that run other programs) contain input or output. Both fortran and matlab can read and write binary files, but we will stick to ascii. It is worth

More information

Introduction to MATLAB

Introduction to MATLAB Chapter 1 Introduction to MATLAB 1.1 Software Philosophy Matrix-based numeric computation MATrix LABoratory built-in support for standard matrix and vector operations High-level programming language Programming

More information

Arrays array array length fixed array fixed length array fixed size array Array elements and subscripting

Arrays array array length fixed array fixed length array fixed size array Array elements and subscripting Arrays Fortunately, structs are not the only aggregate data type in C++. An array is an aggregate data type that lets us access many variables of the same type through a single identifier. Consider the

More information

An Introduction to MATLAB

An Introduction to MATLAB An Introduction to MATLAB Day 1 Simon Mitchell Simon.Mitchell@ucla.edu High level language Programing language and development environment Built-in development tools Numerical manipulation Plotting of

More information

CS1132 Spring 2016 Assignment 2 Due Apr 20th

CS1132 Spring 2016 Assignment 2 Due Apr 20th CS1132 Spring 2016 Assignment 2 Due Apr 20th Adhere to the Code of Academic Integrity. You may discuss background issues and general strategies with others and seek help from course staff, but the implementations

More information

CITS2401 Computer Analysis & Visualisation

CITS2401 Computer Analysis & Visualisation FACULTY OF ENGINEERING, COMPUTING AND MATHEMATICS CITS2401 Computer Analysis & Visualisation SCHOOL OF COMPUTER SCIENCE AND SOFTWARE ENGINEERING Topic 3 Introduction to Matlab Material from MATLAB for

More information

Strings and I/O functions

Strings and I/O functions Davies: Computer Vision, 5 th edition, online materials Matlab Tutorial 2 1 Strings and I/O functions 1. Introduction It is the purpose of these online documents to provide information on Matlab and its

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

SECTION 2: PROGRAMMING WITH MATLAB. MAE 4020/5020 Numerical Methods with MATLAB

SECTION 2: PROGRAMMING WITH MATLAB. MAE 4020/5020 Numerical Methods with MATLAB SECTION 2: PROGRAMMING WITH MATLAB MAE 4020/5020 Numerical Methods with MATLAB 2 Functions and M Files M Files 3 Script file so called due to.m filename extension Contains a series of MATLAB commands The

More information

MATLAB BASICS. M Files. Objectives

MATLAB BASICS. M Files. Objectives Objectives MATLAB BASICS 1. What is MATLAB and why has it been selected to be the tool of choice for DIP? 2. What programming environment does MATLAB offer? 3. What are M-files? 4. What is the difference

More information

OUTLINES. Variable names in MATLAB. Matrices, Vectors and Scalar. Entering a vector Colon operator ( : ) Mathematical operations on vectors.

OUTLINES. Variable names in MATLAB. Matrices, Vectors and Scalar. Entering a vector Colon operator ( : ) Mathematical operations on vectors. 1 LECTURE 3 OUTLINES Variable names in MATLAB Examples Matrices, Vectors and Scalar Scalar Vectors Entering a vector Colon operator ( : ) Mathematical operations on vectors examples 2 VARIABLE NAMES IN

More information

Matlab Guide #4 (created on April 9, 1998) 1

Matlab Guide #4 (created on April 9, 1998) 1 Matlab Guide #4 (created on April 9, 1998) 1 Department of Mathematics and Statistics Canterbury University Maths and Stats Dept MATLAB r Guide for Advanced Users Converting a Diary into a Program (Input

More information

MATLAB = MATrix LABoratory. Interactive system. Basic data element is an array that does not require dimensioning.

MATLAB = MATrix LABoratory. Interactive system. Basic data element is an array that does not require dimensioning. Introduction MATLAB = MATrix LABoratory Interactive system. Basic data element is an array that does not require dimensioning. Efficient computation of matrix and vector formulations (in terms of writing

More information

1 Data Exploration: The 2016 Summer Olympics

1 Data Exploration: The 2016 Summer Olympics CS 1132 Fall 2016 Assignment 2 due 9/29 at 11:59 pm Adhere to the Code of Academic Integrity. You may discuss background issues and general strategies with others and seek help from course staff, but the

More information

COP 3223 Final Review

COP 3223 Final Review COP 3223 Final Review Jennifer Brown December 2, 2018 1 Introduction 1.1 Variables I. How can we store data in a program? Initializing variables with data types A. Which of these are valid names for variables?

More information

Introduction. Like other programming languages, MATLAB has means for modifying the flow of a program

Introduction. Like other programming languages, MATLAB has means for modifying the flow of a program Flow control 1 Introduction Like other programming languages, MATLAB has means for modying the flow of a program All common constructs are implemented in MATLAB: for while then else switch try 2 FOR loops.

More information

GLY Geostatistics Fall Lecture 2 Introduction to the Basics of MATLAB. Command Window & Environment

GLY Geostatistics Fall Lecture 2 Introduction to the Basics of MATLAB. Command Window & Environment GLY 6932 - Geostatistics Fall 2011 Lecture 2 Introduction to the Basics of MATLAB MATLAB is a contraction of Matrix Laboratory, and as you'll soon see, matrices are fundamental to everything in the MATLAB

More information

Lecture 7. MATLAB and Numerical Analysis (4)

Lecture 7. MATLAB and Numerical Analysis (4) Lecture 7 MATLAB and Numerical Analysis (4) Topics for the last 2 weeks (Based on your feedback) PDEs How to email results (after FFT Analysis (1D/2D) Advanced Read/Write Solve more problems Plotting3Dscatter

More information

MATLAB - Lecture # 4

MATLAB - Lecture # 4 MATLAB - Lecture # 4 Script Files / Chapter 4 Topics Covered: 1. Script files. SCRIPT FILE 77-78! A script file is a sequence of MATLAB commands, called a program.! When a file runs, MATLAB executes the

More information

There is also a more in-depth GUI called the Curve Fitting Toolbox. To run this toolbox, type the command

There is also a more in-depth GUI called the Curve Fitting Toolbox. To run this toolbox, type the command Matlab bootcamp Class 4 Written by Kyla Drushka More on curve fitting: GUIs Thanks to Anna (I think!) for showing me this. A very simple way to fit a function to your data is to use the Basic Fitting GUI.

More information

MATLAB: The greatest thing ever. Why is MATLAB so great? Nobody s perfect, not even MATLAB. Prof. Dionne Aleman. Excellent matrix/vector handling

MATLAB: The greatest thing ever. Why is MATLAB so great? Nobody s perfect, not even MATLAB. Prof. Dionne Aleman. Excellent matrix/vector handling MATLAB: The greatest thing ever Prof. Dionne Aleman MIE250: Fundamentals of object-oriented programming University of Toronto MIE250: Fundamentals of object-oriented programming (Aleman) MATLAB 1 / 1 Why

More information

STAT 391 Handout 1 Making Plots with Matlab Mar 26, 2006

STAT 391 Handout 1 Making Plots with Matlab Mar 26, 2006 STAT 39 Handout Making Plots with Matlab Mar 26, 26 c Marina Meilă & Lei Xu mmp@cs.washington.edu This is intended to help you mainly with the graphics in the homework. Matlab is a matrix oriented mathematics

More information

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size]; Arrays An array is a collection of two or more adjacent memory cells, called array elements. Array is derived data type that is used to represent collection of data items. C Array is a collection of data

More information

Chapter 11 Input/Output (I/O) Functions

Chapter 11 Input/Output (I/O) Functions EGR115 Introduction to Computing for Engineers Input/Output (I/O) Functions from: S.J. Chapman, MATLAB Programming for Engineers, 5 th Ed. 2016 Cengage Learning Topics Introduction: MATLAB I/O 11.1 The

More information

Getting To Know Matlab

Getting To Know Matlab Getting To Know Matlab The following worksheets will introduce Matlab to the new user. Please, be sure you really know each step of the lab you performed, even if you are asking a friend who has a better

More information

COP 3223 Final Review

COP 3223 Final Review COP 3223 Final Review Jennifer Brown December 2, 2018 1 Introduction 1.1 Variables I. How can we store data in a program? A. Which of these are valid names for variables? i. 9length ii. hello iii. IamASuperCoolName

More information

Enhanced Debugging with Traces

Enhanced Debugging with Traces Enhanced Debugging with Traces An essential technique used in emulator development is a useful addition to any programmer s toolbox. Peter Phillips Creating an emulator to run old programs is a difficult

More information

Software and Programming 1

Software and Programming 1 Software and Programming 1 Lab 1: Introduction, HelloWorld Program and use of the Debugger 17 January 2019 SP1-Lab1-2018-19.pptx Tobi Brodie (tobi@dcs.bbk.ac.uk) 1 Module Information Lectures: Afternoon

More information

Computers Programming Course 10. Iulian Năstac

Computers Programming Course 10. Iulian Năstac Computers Programming Course 10 Iulian Năstac Recap from previous course 5. Values returned by a function A return statement causes execution to leave the current subroutine and resume at the point in

More information

Chapters covered for the final

Chapters covered for the final Chapters covered for the final Chapter 1 (About MATLAB) Chapter 2 (MATLAB environment) Chapter 3 (Built in Functions):3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.8, 3.9 Chapter 4 (Manipulating Arrays):4.1,4.2, 4.3

More information

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

Constraint-based Metabolic Reconstructions & Analysis H. Scott Hinton. Matlab Tutorial. Lesson: Matlab Tutorial 1 Matlab Tutorial 2 Lecture Learning Objectives Each student should be able to: Describe the Matlab desktop Explain the basic use of Matlab variables Explain the basic use of Matlab scripts Explain the

More information

Outline. Computer programming. Debugging. What is it. Debugging. Hints. Debugging

Outline. Computer programming. Debugging. What is it. Debugging. Hints. Debugging Outline Computer programming Debugging Hints Gathering evidence Common C errors "Education is a progressive discovery of our own ignorance." Will Durant T.U. Cluj-Napoca - Computer Programming - lecture

More information

Using the fprintf command to save output to a file.

Using the fprintf command to save output to a file. Using the fprintf command to save output to a file. In addition to displaying output in the Command Window, the fprintf command can be used for writing the output to a file when it is necessary to save

More information

ECE Lesson Plan - Class 1 Fall, 2001

ECE Lesson Plan - Class 1 Fall, 2001 ECE 201 - Lesson Plan - Class 1 Fall, 2001 Software Development Philosophy Matrix-based numeric computation - MATrix LABoratory High-level programming language - Programming data type specification not

More information

Spring 2010 Instructor: Michele Merler.

Spring 2010 Instructor: Michele Merler. Spring 2010 Instructor: Michele Merler http://www1.cs.columbia.edu/~mmerler/comsw3101-2.html Type from command line: matlab -nodisplay r command Tells MATLAB not to initialize the visual interface NOTE:

More information

Matlab Programming MET 164 1/24

Matlab Programming MET 164 1/24 Matlab Programming 1/24 2/24 What does MATLAB mean? Contraction of Matrix Laboratory Matrices are rectangular arrays of numerical values 7 3 6 2 1 9 4 4 8 4 1 5 7 2 1 3 What are the fundamental components

More information

MATLAB Project: Getting Started with MATLAB

MATLAB Project: Getting Started with MATLAB Name Purpose: To learn to create matrices and use various MATLAB commands for reference later MATLAB built-in functions used: [ ] : ; + - * ^, size, help, format, eye, zeros, ones, diag, rand, round, cos,

More information

MATLAB Introduction To Engineering for ECE Topics Covered: 1. Creating Script Files (.m files) 2. Using the Real Time Debugger

MATLAB Introduction To Engineering for ECE Topics Covered: 1. Creating Script Files (.m files) 2. Using the Real Time Debugger 25.108 Introduction To Engineering for ECE Topics Covered: 1. Creating Script Files (.m files) 2. Using the Real Time Debugger SCRIPT FILE 77-78 A script file is a sequence of MATLAB commands, called a

More information

variables programming statements

variables programming statements 1 VB PROGRAMMERS GUIDE LESSON 1 File: VbGuideL1.doc Date Started: May 24, 2002 Last Update: Dec 27, 2002 ISBN: 0-9730824-9-6 Version: 0.0 INTRODUCTION TO VB PROGRAMMING VB stands for Visual Basic. Visual

More information

Module 6: Array in C

Module 6: Array in C 1 Table of Content 1. Introduction 2. Basics of array 3. Types of Array 4. Declaring Arrays 5. Initializing an array 6. Processing an array 7. Summary Learning objectives 1. To understand the concept of

More information

CS1114: Matlab Introduction

CS1114: Matlab Introduction CS1114: Matlab Introduction 1 Introduction The purpose of this introduction is to provide you a brief introduction to the features of Matlab that will be most relevant to your work in this course. Even

More information

Notes on efficient Matlab programming

Notes on efficient Matlab programming Notes on efficient Matlab programming Dag Lindbo dag@csc.kth.se June 11, 2010 1 Introduction - is Matlab slow? It is a common view that Matlab is slow. This is a very crude statement that holds both some

More information

Image Processing Matlab tutorial 2 MATLAB PROGRAMMING

Image Processing Matlab tutorial 2 MATLAB PROGRAMMING School of Engineering and Physical Sciences Electrical Electronic and Computer Engineering Image Processing Matlab tutorial 2 MATLAB PROGRAMMING 1. Objectives: Last week, we introduced you to the basic

More information

Software and Programming 1

Software and Programming 1 Software and Programming 1 Lab 1: Introduction, HelloWorld Program and use of the Debugger 11 January 2018 SP1-Lab1-2017-18.pptx Tobi Brodie (tobi@dcs.bbk.ac.uk) 1 Module Information Lectures: Afternoon

More information

1 Introduction to MATLAB

1 Introduction to MATLAB 1 Introduction to MATLAB 1.1 Quick Overview This chapter is not intended to be a comprehensive manual of MATLAB R. Our sole aim is to provide sufficient information to give you a good start. If you are

More information

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. C How to Program, 6/e 1992-2010 by Pearson Education, Inc. 1992-2010 by Pearson Education, Inc. 1992-2010 by Pearson Education, Inc. This chapter serves as an introduction to the important topic of data

More information

3D Graphics Programming Mira Costa High School - Class Syllabus,

3D Graphics Programming Mira Costa High School - Class Syllabus, 3D Graphics Programming Mira Costa High School - Class Syllabus, 2009-2010 INSTRUCTOR: Mr. M. Williams COURSE GOALS and OBJECTIVES: 1 Learn the fundamentals of the Java language including data types and

More information

Introduction to MATLAB

Introduction to MATLAB Introduction to MATLAB 1 Introduction to MATLAB A Tutorial for the Course Computational Intelligence http://www.igi.tugraz.at/lehre/ci Stefan Häusler Institute for Theoretical Computer Science Inffeldgasse

More information

Machine Learning Exercise 0

Machine Learning Exercise 0 Machine Learning Exercise 0 Introduction to MATLAB 19-04-2016 Aljosa Osep RWTH Aachen http://www.vision.rwth-aachen.de osep@vision.rwth-aachen.de 1 Experiences with Matlab? Who has worked with Matlab before?

More information

CS 261 Fall Mike Lam, Professor Integer Encodings

CS 261 Fall Mike Lam, Professor   Integer Encodings CS 261 Fall 2018 Mike Lam, Professor https://xkcd.com/571/ Integer Encodings Integers Topics C integer data types Unsigned encoding Signed encodings Conversions Integer data types in C99 1 byte 2 bytes

More information

Teaching Manual Math 2131

Teaching Manual Math 2131 Math 2131 Linear Algebra Labs with MATLAB Math 2131 Linear algebra with Matlab Teaching Manual Math 2131 Contents Week 1 3 1 MATLAB Course Introduction 5 1.1 The MATLAB user interface...........................

More information

1 Logging in 1. 2 Star-P 2

1 Logging in 1. 2 Star-P 2 Quinn Mahoney qmahoney@mit.edu March 21, 2006 Contents 1 Logging in 1 2 Star-P 2 3 Cluster Specifications 9 1 Logging in To log in to the beowulf cluster, ssh to beowulf.csail.mit.edu with the username

More information

Finding, Starting and Using Matlab

Finding, Starting and Using Matlab Variables and Arrays Finding, Starting and Using Matlab CSC March 6 &, 9 Array: A collection of data values organized into rows and columns, and known by a single name. arr(,) Row Row Row Row 4 Col Col

More information

Fundamentals of Programming

Fundamentals of Programming Fundamentals of Programming Lecture 6 - Array and String Lecturer : Ebrahim Jahandar Borrowed from lecturer notes by Omid Jafarinezhad Array Generic declaration: typename variablename[size]; typename is

More information

1 Introduction to MATLAB

1 Introduction to MATLAB 1 Introduction to MATLAB 1.1 General Information Quick Overview This chapter is not intended to be a comprehensive manual of MATLAB R. Our sole aim is to provide sufficient information to give you a good

More information

ONE DIMENSIONAL ARRAYS

ONE DIMENSIONAL ARRAYS LECTURE 14 ONE DIMENSIONAL ARRAYS Array : An array is a fixed sized sequenced collection of related data items of same data type. In its simplest form an array can be used to represent a list of numbers

More information

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL Lesson 06 Arrays MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL Array An array is a group of variables (called elements or components) containing

More information

ES 117. Formatted Input/Output Operations

ES 117. Formatted Input/Output Operations ES 117 Formatted Input/Output Operations fpintf function writes formatted data in a user specified format to a file fid fprintf Function Format effects only the display of variables not their values through

More information

VARIABLES AND TYPES CITS1001

VARIABLES AND TYPES CITS1001 VARIABLES AND TYPES CITS1001 Scope of this lecture Types in Java the eight primitive types the unlimited number of object types Values and References The Golden Rule Primitive types Every piece of data

More information

C introduction: part 1

C introduction: part 1 What is C? C is a compiled language that gives the programmer maximum control and efficiency 1. 1 https://computer.howstuffworks.com/c1.htm 2 / 26 3 / 26 Outline Basic file structure Main function Compilation

More information

Armstrong State University Engineering Studies MATLAB Marina 2D Arrays and Matrices Primer

Armstrong State University Engineering Studies MATLAB Marina 2D Arrays and Matrices Primer Armstrong State University Engineering Studies MATLAB Marina 2D Arrays and Matrices Primer Prerequisites The 2D Arrays and Matrices Primer assumes knowledge of the MATLAB IDE, MATLAB help, arithmetic operations,

More information

Chapter 8 Arrays and Strings. Objectives. Objectives (cont d.) Introduction. Arrays 12/23/2016. In this chapter, you will:

Chapter 8 Arrays and Strings. Objectives. Objectives (cont d.) Introduction. Arrays 12/23/2016. In this chapter, you will: Chapter 8 Arrays and Strings Objectives In this chapter, you will: Learn about arrays Declare and manipulate data into arrays Learn about array index out of bounds Learn about the restrictions on array

More information

CS201 Latest Solved MCQs

CS201 Latest Solved MCQs Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

MATLAB Tutorial. 1. The MATLAB Windows. 2. The Command Windows. 3. Simple scalar or number operations

MATLAB Tutorial. 1. The MATLAB Windows. 2. The Command Windows. 3. Simple scalar or number operations MATLAB Tutorial The following tutorial has been compiled from several resources including the online Help menu of MATLAB. It contains a list of commands that will be directly helpful for understanding

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 7 Array and String Department of Computer Engineering Outline Array String Department

More information

1 >> Lecture 6 2 >> 3 >> -- User-Controlled Input and Output 4 >> Zheng-Liang Lu 367 / 400

1 >> Lecture 6 2 >> 3 >> -- User-Controlled Input and Output 4 >> Zheng-Liang Lu 367 / 400 1 >> Lecture 6 2 >> 3 >> -- User-Controlled Input and Output 4 >> Zheng-Liang Lu 367 / 400 American Standard Code for Information Interchange (ASCII) 2 Everything in the computer is encoded in binary.

More information

Introduction to Matlab/Octave

Introduction to Matlab/Octave Introduction to Matlab/Octave February 28, 2014 This document is designed as a quick introduction for those of you who have never used the Matlab/Octave language, as well as those of you who have used

More information

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics Java Programming, Sixth Edition 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional Projects Additional

More information

MATLAB Introduction. Contents. Introduction to Matlab. Published on Advanced Lab (

MATLAB Introduction. Contents. Introduction to Matlab. Published on Advanced Lab ( Published on Advanced Lab (http://experimentationlab.berkeley.edu) Home > References > MATLAB Introduction MATLAB Introduction Contents 1 Introduction to Matlab 1.1 About Matlab 1.2 Prepare Your Environment

More information

QUIZ: What is the output of this MATLAB code? >> A = [2,4,10,13;16,3,7,18; 8,4,9,25;3,12,15,17]; >> length(a) >> size(a) >> B = A(2:3, 1:3) >> B(5)

QUIZ: What is the output of this MATLAB code? >> A = [2,4,10,13;16,3,7,18; 8,4,9,25;3,12,15,17]; >> length(a) >> size(a) >> B = A(2:3, 1:3) >> B(5) QUIZ: What is the output of this MATLAB code? >> A = [2,4,10,13;16,3,7,18; 8,4,9,25;3,12,15,17]; >> length(a) >> size(a) >> B = A(2:3, 1:3) >> B(5) QUIZ Ch.3 Introduction to MATLAB programming 3.1 Algorithms

More information

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010 CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011 Lectures 1-22 Moaaz Siddiq Asad Ali Latest Mcqs MIDTERM EXAMINATION Spring 2010 Question No: 1 ( Marks: 1 ) - Please

More information

Lab # 02. Basic Elements of C++ _ Part1

Lab # 02. Basic Elements of C++ _ Part1 Lab # 02 Basic Elements of C++ _ Part1 Lab Objectives: After performing this lab, the students should be able to: Become familiar with the basic components of a C++ program, including functions, special

More information

Access to Delimited Text Files

Access to Delimited Text Files Access to Delimited Text Files dlmread(filename, delimiter) reads ASCII-delimited file of numeric data. dlmwrite(filename, M, delimiter) writes the array M to the file using the specified delimiter to

More information

CSE 123. Lecture 9. Formatted. Input/Output Operations

CSE 123. Lecture 9. Formatted. Input/Output Operations CSE 123 Lecture 9 Formatted Input/Output Operations fpintf function writes formatted data in a user specified format to a file fid fprintf Function Format effects only the display of variables not their

More information

Lecture 3: MATLAB advanced use cases

Lecture 3: MATLAB advanced use cases Lecture 3: MATLAB advanced use cases Efficient programming in MATLAB Juha Kuortti and Heikki Apiola February 17, 2018 Aalto University juha.kuortti@aalto.fi Before we begin On this lecture, we will mostly

More information

MBI REU Matlab Tutorial

MBI REU Matlab Tutorial MBI REU Matlab Tutorial Lecturer: Reginald L. McGee II, Ph.D. June 8, 2017 MATLAB MATrix LABoratory MATLAB is a tool for numerical computation and visualization which allows Real & Complex Arithmetics

More information

Originally released in 1986, LabVIEW (short for Laboratory Virtual Instrumentation

Originally released in 1986, LabVIEW (short for Laboratory Virtual Instrumentation Introduction to LabVIEW 2011 by Michael Lekon & Janusz Zalewski Originally released in 1986, LabVIEW (short for Laboratory Virtual Instrumentation Engineering Workbench) is a visual programming environment

More information

Table of Contents. Introduction.*.. 7. Part /: Getting Started With MATLAB 5. Chapter 1: Introducing MATLAB and Its Many Uses 7

Table of Contents. Introduction.*.. 7. Part /: Getting Started With MATLAB 5. Chapter 1: Introducing MATLAB and Its Many Uses 7 MATLAB Table of Contents Introduction.*.. 7 About This Book 1 Foolish Assumptions 2 Icons Used in This Book 3 Beyond the Book 3 Where to Go from Here 4 Part /: Getting Started With MATLAB 5 Chapter 1:

More information

LECTURE 1. What Is Matlab? Matlab Windows. Help

LECTURE 1. What Is Matlab? Matlab Windows. Help LECTURE 1 What Is Matlab? Matlab ("MATrix LABoratory") is a software package (and accompanying programming language) that simplifies many operations in numerical methods, matrix manipulation/linear algebra,

More information

Computer Vision 2 Exercise 0. Introduction to MATLAB ( )

Computer Vision 2 Exercise 0. Introduction to MATLAB ( ) Computer Vision 2 Exercise 0 Introduction to MATLAB (21.04.2016) engelmann@vision.rwth-aachen.de, stueckler@vision.rwth-aachen.de RWTH Aachen University, Computer Vision Group http://www.vision.rwth-aachen.de

More information

MATH36032 Problem Solving by Computer. More Data Structure

MATH36032 Problem Solving by Computer. More Data Structure MATH36032 Problem Solving by Computer More Data Structure Data from real life/applications How do the data look like? In what format? Data from real life/applications How do the data look like? In what

More information

LANGUAGE OF THE C. float fswapvar; /* a normal variable */ float ftemperateeachhour[24]; /* an array */

LANGUAGE OF THE C. float fswapvar; /* a normal variable */ float ftemperateeachhour[24]; /* an array */ C: Part 3 LANGUAGE OF THE C In this, the third part of our C language tutorials, Steve Goodwin looks at more complex data types, extending our temperature conversion idea There is an African tribe with

More information

COGS 119/219 MATLAB for Experimental Research. Fall Functions

COGS 119/219 MATLAB for Experimental Research. Fall Functions COGS 119/219 MATLAB for Experimental Research Fall 2016 - Functions User-defined Functions A user-defined function is a MATLAB program that is created by a user, saved as a function file, and then can

More information

Objectives. In this chapter, you will:

Objectives. In this chapter, you will: Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about

More information

Full file at

Full file at Java Programming, Fifth Edition 2-1 Chapter 2 Using Data within a Program At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional

More information

MATLAB Tutorial III Variables, Files, Advanced Plotting

MATLAB Tutorial III Variables, Files, Advanced Plotting MATLAB Tutorial III Variables, Files, Advanced Plotting A. Dealing with Variables (Arrays and Matrices) Here's a short tutorial on working with variables, taken from the book, Getting Started in Matlab.

More information

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings 19/10/2017 CE221 Part 2 1 Variables and References 1 In Java a variable of primitive type is associated with a memory location

More information

Assignment 1: grid. Due November 20, 11:59 PM Introduction

Assignment 1: grid. Due November 20, 11:59 PM Introduction CS106L Fall 2008 Handout #19 November 5, 2008 Assignment 1: grid Due November 20, 11:59 PM Introduction The STL container classes encompass a wide selection of associative and sequence containers. However,

More information

Lecture 15 MATLAB II: Conditional Statements and Arrays

Lecture 15 MATLAB II: Conditional Statements and Arrays Lecture 15 MATLAB II: Conditional Statements and Arrays 1 Conditional Statements 2 The boolean operators in MATLAB are: > greater than < less than >= greater than or equals

More information