Creating a script create new blank document. Editor options Docking and undocking tabs.

Slides:



Advertisements
Similar presentations
M AT L AB Programming: scripts & functions. Scripts It is possible to achieve a lot simply by executing one command at a time on the command line (even.
Advertisements

Chapter 7 Introduction to Procedures. So far, all programs written in such way that all subtasks are integrated in one single large program. There is.
Why care about debugging? How many of you have written a program that worked perfectly the first time? No one (including me!) writes a program that works.
Chapter 3: Editing and Debugging SAS Programs. Some useful tips of using Program Editor Add line number: In the Command Box, type num, enter. Save SAS.
Using Macros and Visual Basic for Applications (VBA) with Excel
Tutorial 12: Enhancing Excel with Visual Basic for Applications
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 19P. 1Winter Quarter MATLAB: Script and.
Example 2.
EGR 106 – Week 2 – Arrays & Scripts Brief review of last week Arrays: – Concept – Construction – Addressing Scripts and the editor Audio arrays Textbook.
1 Chapter 4 The Fundamentals of VBA, Macros, and Command Bars.
Division Example 2x - 3y + 4z = 10 x + 6y - 3z = 4 -5x + y + 2z = 3 A*X = B where A = B = >> X = A\B X =
Introduction to C Programming
Extending MATLAB Write your own scripts and/or functions Scripts and functions are plain text files with extension.m (m-files) To execute commands contained.
Introduction to programming in MATLAB MATLAB can be thought of as an super-powerful graphing calculator Remember the TI-83 from calculus? With many more.
Programming For Nuclear Engineers Lecture 12 MATLAB (3) 1.
1 Chapter One A First Program Using C#. 2 Objectives Learn about programming tasks Learn object-oriented programming concepts Learn about the C# programming.
Lecture 1: Introduction Lecture series based on the text: Essential MATLAB for Engineers and Scientists By Hahn & Valentine
A First Program Using C#
Visual Basic Chapter 1 Mr. Wangler.
M-files While commands can be entered directly to the command window, MATLAB also allows you to put commands in text files called M- files. M-files are.
Python Programming Fundamentals
MATLAB File Management. MATLAB User File Management Matlab provides a group of commands to manage user files. For more information, type help iofun. pwd.
What is Sure BDCs? BDC stands for Batch Data Communication and is also known as Batch Input. It is a technique for mass input of data into SAP by simulating.
PMS /134/182 HEX 0886B6 PMS /39/80 HEX 5E2750 PMS /168/180 HEX 00A8B4 PMS /190/40 HEX 66CC33 By Adrian Gardener Date 9 July 2012.
Objectives Understand what MATLAB is and why it is widely used in engineering and science Start the MATLAB program and solve simple problems in the command.
© 2008 The McGraw-Hill Companies, Inc. All rights reserved. WORD 2007 M I C R O S O F T ® THE PROFESSIONAL APPROACH S E R I E S Lesson 21 Fields and Forms.
Introduction to Matlab & Data Analysis
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
Shell Scripting Introduction. Agenda What is Shell Scripting? Why use Shell Scripting? Writing and Running a Shell Script Basic Commands -ECHO - REM.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
1 Functions 1 Parameter, 1 Return-Value 1. The problem 2. Recall the layout 3. Create the definition 4. "Flow" of data 5. Testing 6. Projects 1 and 2.
1 The EDIT Program The Edit program is a full screen text editor that allows you to: Create text files Create text files Edit an existing text files Edit.
Introduction to Engineering MATLAB – 6 Script Files - 1 Agenda Script files.
Chapter 9: MuPAD Programming II Procedures MATLAB for Scientist and Engineers Using Symbolic Toolbox.
Introduction to MATLAB Session 3 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2011.
SUNY-New Paltz Computer Simulation Lab Electrical and Computer Engineering Department SUNY – New Paltz “Lecture 6”
Forms and Server Side Includes. What are Forms? Forms are used to get user input We’ve all used them before. For example, ever had to sign up for courses.
1 Κατανεμημένες Διαδικτυακές Εφαρμογές Πολυμέσων Γιάννης Πετράκης.
Diagnostic Pathfinder for Instructors. Diagnostic Pathfinder Local File vs. Database Normal operations Expert operations Admin operations.
Advanced Topics- Functions Introduction to MATLAB 7 Engineering 161.
Creating Graphical User Interfaces (GUI’s) with MATLAB By Jeffrey A. Webb OSU Gateway Coalition Member.
COMP 116: Introduction to Scientific Programming Lecture 11: Functions.
Chapter 0 Getting Started. Objectives Understand the basic structure of a C++ program including: – Comments – Preprocessor instructions – Main function.
Chapter 3 MATLAB Fundamentals Introduction to MATLAB Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
BMTRY 789 Lecture 11: Debugging Readings – Chapter 10 (3 rd Ed) from “The Little SAS Book” Lab Problems – None Homework Due – None Final Project Presentations.
Covenant College November 27, Laura Broussard, Ph.D. Professor COS 131: Computing for Engineers Chapter 5: Functions.
A simple classification problem Extract attributes Pattern Pattern recognition decision x C1 C2.
JDS5 Training Guide. On Start Up you will see this screen click the OK button Click OK.
Introduction to MATLAB Section2, statistics course Third year biomedical dept. Dina El Kholy, Ahmed Dalal.
Debugging tools in Flash CIS 126. Debugging Flash provides several tools for testing ActionScript in your SWF files. –The Debugger, lets you find errors.
ENG College of Engineering Engineering Education Innovation Center 1 Functions 1 in MATLAB Topics Covered: 1.Uses of Functions Organizational Tool.
Lesson 6-Using Utilities to Accomplish Complex Tasks.
Perl Subroutines User Input Perl on linux Forks and Pipes.
L071 Introduction to C Topics Compilation Using the gcc Compiler The Anatomy of a C Program Reading Sections
Chapter 10 Using Macros, Controls and Visual Basic for Applications (VBA) with Excel Microsoft Excel 2013.
Chapter 2 Build Your First Project A Step-by-Step Approach 2 Exploring Microsoft Visual Basic 6.0 Copyright © 1999 Prentice-Hall, Inc. By Carlotta Eaton.
Part 1 Learning Objectives To understand that variables are a temporary named location to store data and that programmers work with different data types.
Release Numbers MATLAB is updated regularly
Matlab Training Session 4: Control, Flow and Functions
Eclipse Navigation & Usage.
Basic operations in Matlab
Scripts & Functions Scripts and functions are contained in .m-files
User Defined Functions
MATLAB Programs Chapter 6 Attaway MATLAB 4E.
Functions In Matlab.
CSCI N317 Computation for Scientific Applications Unit 1 – 1 MATLAB
Scripts In Matlab.
MATLAB Programs Chapter 6 Attaway MATLAB 5E.
Creating a script create new blank document.
Presentation transcript:

Creating a script create new blank document

Editor options Docking and undocking tabs

COMMAND WINDOW versus EDITOR

Command window Commands are executed immediately when you press Return Variables that are created appear in the Workspace Cannot define functions here

Editor Commands are not executed right away*. They will only be executed when you invoke the saved file from the Command Window. When you do that, everything in the file will be executed, in order. Variables created here will not appear in the Workspace before executing You may define functions here * if you want one or more lines from a file in the Editor to be executed immediately, you can do that: Highlight the part you want to execute Text menu -> Evaluate selection…. or press Shift + F7 (on mac)

Writing scipts: M-Files M-files are text files containing Matlab code (i.e. not just data) and are created/edited using Matlab Editor The files are saved under the name *.m ( rather than *.mat) NB A key problem that new users often face is that the directory in which the file was stored is not the current directory in Matlab. Check on this!!!!

Your first script % My first script x = 5; y = 6; z = x + y >> myFirst z = 11 Save script as “myFirst.m”

Your first script % My first script x = 5; y = 6; z = x + y >> myFirst z = 11 Save script as “myFirst.m” EDITOR COMMAND WINDOW

Comments Comments start with % and appear in green in the editor Can appear on their own line, or on a line with code provided they are after the semicolon Hint: you may use comments to temporarily disable lines of code

M-files example (script/module) write a program to display the number of whole days between now and the end of the year (days2go.m): date_now=clock; next_year=date_now(1)+1; date_eoy=[next_year ]; diff_time=etime(date_eoy,date_now); days=floor(diff_time/(60*60*24)); disp(sprintf(‘Days between now and end of year: %d’,days));

M-files example (script/module) clear all; close all; % remove old variables & close old graphic windows date_now=clock; % get current date and time next_year=date_now(1)+1; % calculate next year date_eoy=[next_year ]; % date on Jan 1 st midnight (end of year) diff_time=etime(date_eoy,date_now); % difference in sec between eoy/now days=floor(diff_time/(60*60*24)); % convert to days and round disp(sprintf(‘Days between now and end of year: %d’,days)); % print out result >> days2go

What is a function? A function is a self-contained piece of code that accomplishes a specific function It may take in certain variables (parameters) and return results It has an INPUT, an OUTPUT and a name.. It has it’s own, local (vs. global) variables

Function declarations code folding result of the function name of the function parameters passed to the function All functions must be declared, that is, introduced in the proper way. INOUT

Function declarations function printAName(name) %Not very exciting. Just prints a name. fprintf(‘The name is: %s\n’,name); Functions may return no variables: Or several: function [avg,biggest,smallest] = getSomeStats(x) %Return some statistics on vector x avg = mean(x); biggest= max(x); smallest = min(x);

Scripts and Functions Example Place the following code into a ‘.m’ file, give it the name mymultiply.m and call it from the command line: function r = mymultiply(a, b) % function definition r = a*b; % the actual code that does something return % not really needed, but good practice

Scripts and Functions Q: What is the difference between a Matlab script and a Matlab function ? A: Variables in Matlab scripts are held in the main Workspace, and are always visible to you from the Workspace. Variables defined and used in functions are “private”, i.e. in context only within the “scope” of that function (i.e. In the function, as it is being executed). Commands in the Workspace cannot see variables in the function, and vice versa. You can think of a function as having its own private Workspace.

Function variables are private function private(x) x=1; y=2; disp(sprintf(‘x = %d’, x)) disp(sprintf(‘y = %d’, y)) return >> clear all >> x=0 >> private(x) >> x >> y

Scripts and Functions Q: So, if scripts and functions can’t see each others’ variables, what is the point ? A: Privacy of functions guarantees that functions and scripts can’t accidentally modify variables in each other (very useful to avoid bugs in complex programs!) Q: How can we access variables used by functions, and how can we make use of functions ? A: By passing arguments in and out of the functions; this can be done either from the main command line, or from other functions, without limit.

Global Variables If you really want more than one function to share a single copy of a variable, you CAN declare the variable as global in all functions that require access. Do the same thing at the command line if you want the main Workspace to access the variable function r = mymultiply(a, b) global c; r = a*b + c; return At the Workspace command prompt, you could enter c = 34 (for example), then call mymultiply with the a and b arguments that you wish to pass. From experience, I avoid the use of global variables – because they have to be declared in every function that uses them, you are better off passing the variable into the function anyway. Top Tip: If the number of arguments you are passing into a function, or extracting at the output is getting very large, consider placing the arguments into the fields of a structure.

Coding style Your code needs to be readable by other humans Never trust yourself to remember anything - just because something appears obvious now does not mean it will in the future, or to someone else. Use comments to explain what you are doing in English. In a collaborative laboratory setting your code is not just for you: – you need to write to allow other people to update and change your code for their purposes – you need to write your code to be as flexible as possible. this means we will expect the code to be transported to other machines, and other environments

Coding style %set up standard presentation parameters instructionScreenTime = 10; %how long the instructions will stay on, in seconds stimulusScreenTime = 4; %how long the stimulus will stay on, in seconds acceptableResponses = [1,2]; %which responses buttons the subject may press %convert times from seconds into frames instructionScreenTime = instructionScreenTime/frameRate; stimulusScreenTime = stimulusScreenTime/frameRate; ist= 10; sst= 4; r= [1,2]; ist = ist/fr; sst = sst/fr;

Coding style %add two to the instruction screen time instructionScreenTime = instructionScreenTime + 2;%here we are adding two %add time to the instruction screen time to account for %the additional time needed by this subject population instructionScreenTime = instructionScreenTime + 2; Make your comments informative

Coding style

Debugging Matlab includes a built-in debugging tool to help you diagnose errors in your code

NOTE: We are calling another function that we defined in the same file. In a script, we can call functions that are: -built-in Matlab functions -defined within the same file -in other files in the same folder -in other files in folders that are in the PATH

>> debugDemo('SB02') Error using fprintf Function is not defined for 'cell' inputs. Error in debugDemo>printSomething (line 19) fprintf('This is your string: %s\n',stringToPrint); Error in debugDemo (line 11) printSomething(myConditions); Debugging Links to the help file for that function Links to the line in the script where the problem occurred proximal cause of error distal cause of error

BREAKPOINTS

Debugging >> debugDemo('SB02') 11 printSomething(myConditions); K>> K>> prompt indicates that are are in debug mode This is the line where the script has paused (we set a breakpoint here). The line number is a link to the line in the editor. Workspace shifts to showing all the variables in memory inside the function

GREEN ARROW SHOWS WHERE WE ARE PAUSED

Exercises Write a function called ‘average’ that returns the mean of a list of numbers (use built-in functions sum() and length()..). Include comments (that will appear with the help command). Write a function with no input values and a function with no output values

Exercises Modify days2go.m such that it prints out the no of days from the beginning of the year and save the new M-file as daysgone.m (use comments). Convert the above two scripts to a function that gives both the no of days passed from your last birthday and the days remaining till your next birthday. Your birthday should be given to the function as a vector of length 3 (year, month, date). Write a function called ‘stat’ that returns both the mean & standard deviation of a list of numbers (use built-in functions sum() and length()..). Debug debugDemo.m so that it works! Put comments after each command & get rid of commands which are not necessary..