Spring 2010 Instructor: Michele Merler.

Similar documents
Beyond the Mouse A Short Course on Programming

Lecture 7. MATLAB and Numerical Analysis (4)

COMS 3101 Programming Languages: MATLAB. Lecture 2

COMS 3101 Programming Languages: MATLAB. Lecture 3

Spring 2010 Instructor: Michele Merler.

5. MATLAB I/O 1. Beyond the Mouse GEOS 436/636 Jeff Freymueller, Sep 26, The Uncomfortable Truths Well, hop://xkcd.com/568 (April 13, 2009)

Basic Plotting. All plotting commands have similar interface: Most commonly used plotting commands include the following.

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

Matlab programming, plotting and data handling

Fö 6: Filhantering. DN1212 Numeriska metoder och grundläggande programmering. Pawel Herman. KTH/CB

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

Spring 2010 Instructor: Michele Merler.

Programming in Mathematics. Mili I. Shah

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

Importing and Exporting Data

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

Chemical Engineering 541

Information for Candidates. Test Format

Using files. Computer Programming for Engineers (2014 Spring)

Matlab Programming Arrays and Scripts 1 2

Working with Excel Files. a = round(rand(5,3)*100) xlswrite('rand.xlsx',a) b = xlsread('rand.xlsx')

Chapters covered for the final

MATLAB User-defined functions, Data Input/Output. Edited by Péter Vass

ES 117. Formatted Input/Output Operations

Strings and I/O functions

Grace days can not be used for this assignment

1 Data Exploration: The 2016 Summer Olympics

W1005 Intro to CS and Programming in MATLAB. Data Structures. Fall 2014 Instructor: Ilia Vovsha. hep://

Access to Delimited Text Files

Low-Level File I/O. 1. Open a file. 2. Read or write data into the file. 3. Close the file. Zheng-Liang Lu 1 / 14

LECTURE 1. What Is Matlab? Matlab Windows. Help

Using the fprintf command to save output to a file.

Beyond the Mouse A Short Course on Programming

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

EGR 102 Introduction to Engineering Modeling. Lab 05A Managing Data

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

Flow Control and Functions

Introduction to MATLAB LAB 1

Matlab course at. P. Ciuciu 1,2. 1: CEA/NeuroSpin/LNAO 2: IFR49

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

Interactive MATLAB use. Often, many steps are needed. Automated data processing is common in Earth science! only good if problem is simple

Homework 1 Description CmpE 362 Spring Instructor : Fatih Alagoz Teaching Assistant : Yekta Said Can Due: 3 March, 23:59, sharp

Laboratory 1 Octave Tutorial

CANDIDATE INFORMATION

ENG Introduction to Engineering

Course Layout. Go to follow instr. Accessible within campus (only for the first download)

Introduction to Matlab

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

Basic MATLAB Intro III

Chapter 11 Input/Output (I/O) Functions

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

MATLAB Functions and Graphics

More on Functions. Dmitry Adamskiy 07 Dec 2011

Computational Methods of Scientific Programming

School Of Electrical, Computer & Telecommunications Engineering UOW. Training Lab. Introduction to MATLAB. Version: 1.1

MATLAB INTRODUCTION. Matlab can be used interactively as a super hand calculator, or, more powerfully, run using scripts (i.e., programs).

Introduction to Matlab

4.0 Programming with MATLAB

ESS 116 Introduc)on to Data Analysis in Earth Science

INTERNATIONAL EDITION. MATLAB for Engineers. Third Edition. Holly Moore

Programming in MATLAB

An Introduction to Programming in MATLAB Michael Sockin February 20, 2015

Singular Value Decomposition (SVD) 1

Quick MATLAB Syntax Guide

A = [1, 6; 78, 9] Note: everything is case-sensitive, so a and A are different. One enters the above matrix as

MATLAB Basics EE107: COMMUNICATION SYSTEMS HUSSAIN ELKOTBY

MATLAB. MATLAB Review. MATLAB Basics: Variables. MATLAB Basics: Variables. MATLAB Basics: Subarrays. MATLAB Basics: Subarrays

Matlab Introduction. Dr. Antonio A. Trani Professor Dept. of Civil and Environmental Engineering. Virginia Tech (copyright A.A.

Introduction and MATLAB Basics

CSE/Math 485 Matlab Tutorial and Demo

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

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

Introduction to MATLAB

Introduction to MATLAB

Machine Learning Exercise 0

Eng Marine Production Management. Introduction to Matlab

MATLAB. Input/Output. CS101 lec

How to learn MATLAB? Some predefined variables

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

QUICK INTRODUCTION TO MATLAB PART I

MATLAB GUIDE UMD PHYS401 SPRING 2011

Introduction to MATLAB

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing

MATLAB Tutorial. Primary Author: Shoumik Chatterjee Secondary Author: Dr. Chuan Li

SBT 645 Introduction to Scientific Computing in Sports Science #6

MATLAB SUMMARY FOR MATH2070/2970

Computer Vision 2 Exercise 0. Introduction to MATLAB ( )

Chapter 3: Introduction to MATLAB Programming (4 th ed.)

Appendix A. Introduction to MATLAB. A.1 What Is MATLAB?

Intro Chapter 1 Demo Help Lookfor Doc Quit exit Variable variablename = expression = assignment operator, initializing Incrementing Identifier names

10 M-File Programming

1 Introduction. 2 Useful linear algebra (reprise) Introduction to MATLAB Reading. Spencer and Ware (2008), secs. 1-7, 9-9.3,

Programming 1. Script files. help cd Example:

Lecture 2: Advanced Programming Topics

String Manipulation. Chapter 7. Attaway MATLAB 4E

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

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

EE168 Handout #6 Winter Useful MATLAB Tips

PART 1 PROGRAMMING WITH MATHLAB

MATLAB GUIDE UMD PHYS401 SPRING 2012

Transcription:

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: this works only for Linux Tells MATLAB to execute the following command This will start MATLAB, open its environment without showing the GUI, and execute the specified command within the environment NOTE: MATLAB will stay open after this!!! We have to explicitly close the environment

Example 1: matlab -nodisplay r x=3 Example 2: Prepare script myscript.m x = rand(30); save('my_x','x'); matlab -nodisplay r myscript

Example 1: matlab -nodisplay r x=3 Example 2: Prepare script myscript.m x = rand(30); save('my_x','x'); exit matlab -nodisplay r myscript

MATLAB stores data in specific files, with extension.mat save Example General Form x = rand(7, 3); y = cool ; save( myfile, x ); save( namefile(.mat), variable ); save( myfile2, x, y ); save( namefile(.mat), var1, var2, ); load Example General Form load myfile2; load namefile(.mat) ; newx = load( myfile2, x ); var = load( namefile(.mat) );

MATLAB allows scripts or functions to read data inserted by users in the command window, using the function input() input() Example 1 General Form weight = input( Insert weight: ); var = input( string ); Example 2 General Form name = input( Insert name:\n, s ); var = input( string, s ); This specifies that var is going to be a string

fopen fid = fopen( myfile.txt, r ) File ID Filename Mode: r read w write a - append Operations on file fid fclose fclose(fid)

Example fid = fopen( myfile.txt, r ); while 1 tline = fgetl(fid); if ~ischar(tline), break, end disp(tline) end fclose(fid);

Example fid = fopen( myfile.txt, r ); while 1 tline = fgetl(fid); if ~ischar(tline), break, end disp(tline) end fclose(fid); Reads single line in file Checks format of argument

MATLAB has special functions to deal with files containing formatted data dlmread data = dlmread('myfile.txt',' ', 2, 1); data = dlmread('myfile.txt',' ', [2 1 4 2]); dlmwrite

MATLAB has special functions to deal with files containing formatted data dlmread First row data = dlmread('myfile.txt',' ', 2, 1); Filename Delimiter First column data = dlmread('myfile.txt',' ', [2 1 4 2]); Rows Columns dlmwrite

MATLAB has special functions to deal with files containing formatted data dlmread data = dlmread('myfile.txt',' ', 2, 1); Starts counting with 0! data = dlmread('myfile.txt',' ', [2 1 4 2]); dlmwrite

MATLAB has special functions to deal with files containing formatted data dlmread data = dlmread('myfile.txt',' ', 2, 1); data = dlmread('myfile.txt',' ', [2 1 4 2]); dlmwrite dlmwrite('myfile2.txt',data, \t', -append'); Filename Variable Delimiter

MATLAB has special functions to deal with files containing formatted data csvread csvwrite For comma separated files datacsv = csvread('myfile.csv') datacsv2 = dlmread('myfile.csv',',')

Images are matrices Color images are [nxmx3] matrices Grayscale images are [nxm] matrices R G B x Reading Images imread Im = imread( mypic.jpg ); 1,1 Saving Images imwrite imwrite(im, mypic2.png ); y

Structs are data structures that allow to keep different data types in the same variable Struct s = struct('field1', var1, 'field2', var2,...); Example s = struct( num', [1:10], str', cool ); s.str s.newfield = 3; Note: when we save multiple variables in a.mat file, and later try to load them assigning to a single variable, they get saved as fields of a struct

Cells also allow to keep different data types in the same variable Cell c = cell(n); c = cell(m,n); c = { one, two, three }; c = { one, two,3}; c = {[1] [2 3 4]; [5; 9] [6 7 8; 10 11 12]}; for in=1:5 c{in} = rand(in,2); end

Cell2mat for in=1:5 c{in} = rand(in,2); end cmat = cell2mat(c); c Error! cmat = cell2mat(c ); Matrices dimensions must agree! cmat

cell2struct fields = { number, name, value } c = { one, Luke,3; two, Don,7}; cstruct = cell2struct(c,fields,2);

textscan() Read data from text file, convert, and write to cell array fid = fopen( myfile.txt ); C = textscan(fid,'format'); fclose(fid);

textscan() inputtextscan.txt Sally Level1 12.34 45 1.23e10 inf NaN Yes Joe Level2 23.54 60 9e19 -inf 0.001 No Bill Level3 34.90 12 2e5 10 100 No Read data from text file, convert, and write to cell array Example fid = fopen( inputtextscan.txt ); C = textscan(fid,'%s %s %f32 %d8 %u %f %f %s'); fclose(fid); C = [1x8] cell {3x1 cell} {3x1 cell} [3x1 single] [3x1 int8] [3x1 uint32] [3x1 double] [3x1 double] {3x1 cell} %s %s %f32 %d8 %u %f %f %s

lower S = ABCDE ; sl = lower(s); abcde upper Sagain = upper(sl); strtok S = try it out! It is fun ; [part res] = strtok(s,! ); try it out! It is fun

str(n)cmp(i) res = strcmp( hi, Hi ); 0 res = strcmpi( hi, Hi ); 1 strfind S = this is my long long string ; index = strfind(s, i );

str2num S = 334345 ; snum = str2num(s); num2str n = 33; s = str2num(n);

interface Insert/remove breakpoint Continue, step, jump, stop debugging

Definition function [ret1, ret2, ] = namef(input1, input2, ) The.m file containing the function must be named namef.m Dynamic management of input/output: nargin, nargout varargin, varargout Return number of inputs and outputs Allow number of inputs and outputs to be determined by the function call

Example 1 file circ.m function [diam, area] = circ(radius) diam = radius*2; area = pi*(radius^2); Example 2 file circ2.m function [varargout] = circ2(varargin) r= zeros(nargin,1); for in=1:nargin r(in) = varargin{in}; end diam = r*2; area = pi*(r.^2); varargout = {diam, area};

We can define multiple Functions in the same fun.m file, as long as: fun.m is a function file, not a simple script the functions are called only by the main function of fun.m, which is fun()

Write 2 functions for time conversion hms2secs(vec) which takes as input a [1x3] vector vec containing values of hour, minutes and seconds and returns a scalar with the total number of seconds secs2hms(s) which takes as input a scalar s with a number of seconds and converts it into a [1x3] vector containing values of hour, minutes and seconds

Write 2 functions for time conversion hms2secs(vec) function [s] = hms2secs(vec) s = vec(1)*3600 + vec(2)*60 + vec(3); secs2hms(s) function [vec] = secs2hms(s) vec(1) = floor(s/3600); vec(2) = floor((s-vec(1)*3600)/60); vec(3) = s - vec(1)*3600 - vec(2)*60;

Exercise 1 Consider the series n x n i 0 1 1 x if x 1 Compute it for x = 0.63 and n=10,20,100 Compare the values obtained with the limit value

Exercise 2 x has 500 equally spaced elements in the range [-2:2] Plot the function y=e x -x-1.5, with red line and diamond shaped blue markers Put title and axes labels in the figure Find the value of x at the global minimum of the function

Exercise 3 Generate a vector vec with elements in increasing order from 1 to 10, at intervals of 2 Write a loop in which at every iteration a [7x1] matrix A is initialized with random numbers between 0 and 30 Keep iterating until you can access the element of vec located in the position corresponding to the value of the third element of A Keep track of the number of failed attempts by printing a comment to command window at each iteration

Exercise 4 Load the peaks built in MATLAB variable into the variable Z Plot its surface in the x interval [20 30] and y interval [30 50] Find the peak in the interval with the MATLAB interface tool, without writing code Plot in the same graph a surface parallel to the xy axes and passing through the peak

Exercise 1 x = 0.63; limit = 1/(1-x); for n=[10 20 100] expterm = [0:n]; s = sum(x.^expterm); disp(abs(limit - s)) end

Exercise 2 x = linspace(-2,2,500); y = exp(x)-x-1.5; plot(x,y, rdb ); title( y ); xlabel( x ); ylabel( f(x) ); [minval minloc ] = min(y); disp(x(minloc))

Exercise 3 c=1; vec = [1:10]; while(c) A = floor(30*rand(7,1)); try t = vec(a(3)); s = c; c = 0; catch fprintf( Attempt number %d failed\n,c); c = c+1; end end fprintf( Attempt number %d succeeded\n,s);

Exercise 4 Z = peaks; surf(z); xlim([20 30]) ylim([30 50]) hold on Z2 = 8.075 * ones(size(z)); mesh(z2) hold off

In class, in front of computer 40 minutes Arguments: everything done so far Closed notes, closed web, closed phones Only MATLAB (with MATLAB help) Upload code to CourseWorks when done

Due at beginning of class, no exceptions Put your code (.m files) and additional files in a single folder, name it youruni_hw_x and zip it Upload the zipped folder to CourseWorks Bring a printout of your code to class Good Luck and have fun! 30