Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Matlab Variables and Data Manipulation: Default Configuration, Naming, and Calculations - , Assignments of Computer Science

An introduction to using matlab for defining variables, performing calculations, and working with matrices. Topics covered include default window configuration, naming rules, scalar and vector assignments, simple data plots, and calculating with matlab. It also includes a practice exercise for testing allowed variable names.

Typology: Assignments

2009/2010

Uploaded on 02/24/2010

koofers-user-26o
koofers-user-26o šŸ‡ŗšŸ‡ø

10 documents

1 / 20

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
CSCD 309 – Scientific
Programming
Module 2: The Matlab
Environment (Chpt 2)
©2008-2009 Prentice Hall, Paul Schimpf
All rights reserved
All
rights
reserved
.
No portion of this presentation may be reproduced, in whole or in
part, in any form whatsoever, without the express permission of the
author. Students enrolled in this class are hereby granted
permission to reproduce this presentation for personal use only.
Default Window Configuration
•clc will clear the
command window
•Octave opens with just a Command Window
–commands are typed, interactively, into this window
–once you hit enter, the command is processed
–You can retrieve previous commands (including from previous
sessions) using the up cursor, and can edit commands before
entering them
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14

Partial preview of the text

Download Matlab Variables and Data Manipulation: Default Configuration, Naming, and Calculations - and more Assignments Computer Science in PDF only on Docsity!

CSCD 309 – Scientific

Programming

Module 2: The Matlab

Environment (Chpt 2)

Ā© 2008-2009 Prentice Hall, Paul Schimpf All rights reservedAll rights reserved.

No portion of this presentation may be reproduced, in whole or in part, in any form whatsoever, without the express permission of the author. Students enrolled in this class are hereby granted permission to reproduce this presentation for personal use only.

Default Window Configuration

• clc will clear the

command window

• Octave opens with just a Command Window

  • commands are typed, interactively, into this window
  • once you hit enter, the command is processed
  • You can retrieve previous commands (including from previous sessions) using the up cursor, and can edit commands before entering them

Defining variables

Scalar

Row Vector

Column Vector

Note:

"=" means "gets" or Column Vector "is assigned"

Matrix

g

Assignment Operator

• To define a variable , a, we might type

a=1+

  • the expressionp on the RHS will be evaluated, and the result (3), ( ) will be assigned to the variable named "a"

• In algebra the equation

x=y+

  • means that both sides are the same
  • in Matlab (and many other programming languages) this is an instruction that tells the machine to store the result of the RHS calculation in a memory location called "x"

• Is that really different?

  • Yes! For example, in algebra this statement must be false: x=x+
  • In Matlab that is perfectly legitimate, and replaces the value in variable x with a new value equal to x+1, which has the effect of adding 1 to whatever value x currently holds

Naming Variables

• All names must start with a letter

• They may contain letters, numbers and

the underscore ( _ )( )

• Names are case sensitive

• There are certain keywords you can’t use

  • the "iskeyword" command will list them for you
  • 'break', 'case', 'catch', 'classdef', 'continue', 'else',

'elseif', 'end', 'for', 'function', 'global', 'if', 'otherwise',elseif , end , for , function , global , if , otherwise ,

'parfor', 'persistent', 'return', 'switch', 'try', 'while'

  • Octave returns a somewhat larger list

• clear will remove that variable

• clear alone will remove all variables

Reassigning names

• Matlab will let you reuse built-in

function names and variables

  • you can, for example, assign a value to what was ayou can, for example, assign a value to what was a

function name, changing it to a variable:

iskeyword = 1

sin = 3

  • Matlab also has built-in variables, such as:

>> pi

ans =

  • reassigning those names to a different value or to a

function would be a bad idea

• You can clear these to their defaults

using

>> clear

Practice Exercise 2.

• Which of the following names are

allowed?

  • note that you can test them with the isvarnamenote that you can test them with the isvarname,

iskeyword, and which commands

  • to get help on a command, type "help " test Test if my-book my_book

x

x

Thisisoneverylongnamebutisitstillallowed? 1stgroup group_one zzaAbc z34wAwy?12# sin log

x

x

x x

bad idea

Calculations

• You can use MATLAB like you’d use a

calculator

• Order of precedence is algebraic - same as

you’ve probably learned elsewhere

• Same as your calculator

  • Parentheses first

ans=

Parentheses first

  • Exponentiation
  • Multiplication / division
  • Addition / subtraction

• Whitespace is ignored

Example: surface area of a cylinder

SA = π r + π rh = π r r + h

• Using Matlab as a glorified calculator is fine,

but its real strength is in matrix manipulations

Matrices

• This is the basic data type of Matlab

• • Two-dimensional group of numbersTwo dimensional group of numbers

arranged into rows and columns

• A Single Value (Scalar)

  • is a matrix with one row and one column

• Vector (One dimensional matrix)

  • – is a matrix with a single row or a single columnis a matrix with a single row or a single column

Row Vector

To create a row vector, enclose a list of values in brackets

You could also separate the values with a comma

Column Vector

Use a semicolon as a delimiter to create a new row

Range Shortcuts

The default increment is 1 but ifThe default increment is 1, but if you want to use a different increment put it between the first and final values

Autogenerated vector spacings

• You can include mathematical operations

inside a matrix definition statement:

a = [0: pi/10: pi]a = [0: pi/10: pi]

• linspace(x1, x2, n)

  • generates a vector with n entries, linearly (equally)

spaced from x1 to x2 (inclusive)

>> linspace(1, 10, 3)

ans = 1.0000 5.5000 10.

• logspace(x1, x2, n)

  • generates a vector with n entries, with

logarithmically equal spacing from 10 x1^ to 10 x

>> logspace(1, 3, 3)

ans = 10 100 1000

Mixed calculations

• Matrices can be used in many calculations with scalars

• Addition and subtraction are straightforward

  • matrices (and vectors) must be the same size to be added ormatrices (and vectors) must be the same size to be added or subtracted
  • a scalar is added to or subtracted from each element of a matrix of vector

• Multiplication (and division) are a little trickier

  • a scalar multiplies or divides every element of a matrix or vector
  • for matrices, * means to perform a matrix multiplication, which requires that the inner dimensions must agreerequires that the inner dimensions must agree
  • IOW, if matrix A is (m x n) and matrix B is (p x q), then A*B can only be performed if n==p, and the result is an m x q matrix
  • the same holds for vectors, the only distinction being that one of the dimensions is 1
  • we'll talk about matrix division later

Element-by-element

• Element by element multiplies and divides

between matrices are rare, but can be

achieved with special operators:

.* element-by-element multiply

./ element-by-element divide

  • the matrices must be the same size

• Exponentiation: a^b

  • at least one of the two operands must be a scalar
  • if a matrix is involved it must be squareif a matrix is involved, it must be square

• Element-by-element exponentiation: a .^ b

  • if b is a scalar, then each element of a is raised to

that power

  • if both operands are matrices or vectors, the

dimensions much match

Transpose Operator

The transpose operator exchangesh rows and columns

Transposing Vectors

table =[degrees;radians]’ would have given the same result

Transposing Matrices

Number Formats

• Scientific Notation

  • although you can enter any number in decimal

notation it isn’t the best way to represent large or smallnotation, it isn t the best way to represent large or small

numbers

  • in Matlab, values in scientific notation are designated

with an e between the decimal number and exponent

(your calculator probably uses similar notation)

• Several display formats are available

  • the default format is called short
  • an integer is displayed without trailing zeros
  • floating pt number is displayed with four decimal digits

• Matlab uses double precision floating

point numbers for its calculations

Really Big and Really Small

• When numbers

become too large or

ttoo small to display ll t di l

using the default

format, they are

displayed in scientific

notation

• You can force

scientific notation forscientific notation for

all numbers with:

  • format short e
  • format long e

Common Scale Factor

• For long and

short formats, a

common scalecommon scale

factor is applied

to the entire

matrix if some

of the elements

become very

large, or very

smallsmall. This This

scale factor is

printed along

with the scaled

values.

Two other formats

• format +

  • displays onlydisplays only

the sign of the

result (blank

for zero)

• format rat

  • approximates

the result as a

ratio of smallratio of small

integers.

Saving Variables

  • You can save all or just some of your vars to a file
  • • Matlab adds theMatlab adds the extension .mat
  • Octave currently adds no extension (I suggest using .oct or .dat)
  • Matlab will start up in thatup in that directory when you double-click a .mat file
  • Octave doesn't presently do that, but you can change the default startup directory by editing the shortcut properties or putting a cd command in the startup file (c:\Program Files\Octave.octaverc)

Beware Octave Behavior

• Let’s say you:

>> edit TestMe

  • that will without asking create a file called TestMe m inthat will, without asking, create a file called TestMe.m in

the current editor directory

  • Suppose you put a bunch of code in there

• Then suppose you:

>> edit testme

  • Octave doesn’t find a file by that name (the case is

different)

  • so it decides it needs to create one
  • but it uses case-independent system calls to do it, which

results in overwriting the existing file TestMe.m

  • destroying all your previous coding in the process
  • I’ve been burned enough that I use a separate editor

Octave Editor Home Directory

• Defaults to the octave directory that is

created in your My Documents folder

• You can query this with the command:

edit get home ans = C:\Documents and Settings\pschimpf\octave

• I prefer that my m-files be created in my

current working directory. You can change

this with the command:

edit home>> edit home.

• Unfortunately, this parameter is not retained

between sessions, so you might want to put

that command in the startup file (c:\Program

Files\Octave.octaverc)

Octave m-files

• if you just want a

script, remove this

template code for

• What's the diff?

Th d i

template code for

a function

  • you'll often want a function, but we haven't talked about those yet
  • The commands in a script can be "played" by simply typing the filename in the command window
  • A function typically has parameters passed in, and may return a value
  • The variables created in a function are local (they go away, and are no longer visible) when the function returns

Comments

• Be sure to comment your code

  • In Matlab, comments begin with %In Matlab, comments begin with %
  • In Octave, comments begin with % or #

• Minimal comment requirements:

  • Name
  • Date
  • Assignment #
  • Descriptions of what you are doing and why,

sprinkled at appropriate places throughout your

code

  • see template file for HW #