New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here


by: Eunice Schoen
Eunice Schoen
GPA 3.61

Charles Pruett

Almost Ready


These notes were just uploaded, and will be ready to view shortly.

Purchase these notes here, or revisit this page.

Either way, we'll remind you when they're ready :)

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Charles Pruett
Class Notes
25 ?




Popular in Course

Popular in Mathematics (M)

This 9 page Class Notes was uploaded by Eunice Schoen on Saturday September 26, 2015. The Class Notes belongs to MATH 341 at James Madison University taught by Charles Pruett in Fall. Since its upload, it has received 33 views. For similar materials see /class/214022/math-341-james-madison-university in Mathematics (M) at James Madison University.


Reviews for NON


Report this Material


What is Karma?


Karma is the currency of StudySoup.

You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 09/26/15
A comparison of F and MATLAB as programming languages This is meant as a comparison of the two languages not as a tutorial It might also be useful as a reminder of the specific form of some statements I use F for the fortran examples because there is generally only one prefered way to write each statement At the end are sections with short summaries of things that are available in one language but not in the other ie in F modules in MATLAB 2 and 3D graphics If you want examples of operator overloading bitwise operations pointers and linked lists in F you will have to go to the references such as quotProgrammer s Guide to F by Walter S Brainerd et al A free F compiler for Windows and linux is available at wwwfortran com operators standard IO 7 file IO Optional parts of statements are written in italics underlined F FORTRAN 7 built in functions 8 Contents 2 flow of control 3 work with arrays 4 structures 5 functions as ar s MATLAB Names Treat it as case insensitive but F insists that F keywords are all lower case 31 characters 1St is a letter Case sensitive namelengthmax probably 31 or 63 depending on the specific version 1St is a letter Variables Strong typing F requires variable declarations with array dimension allocations dimension is ok in a procedure and there is a special method for allocatable arrays integer parameter days365weeks52 integer 110 initial value but it can change realkindquadpublicparameter g98 real dimension9499099 xy real dimensionl4 Z l 23 40 95 1 complex dimensionlOlO root characterlen20 name characterlen parameter logical yesgno fmtquot3f83quot No declarations needed real most of the time complex if necessary special integer and high precision types available Chmacwr a39time399 a3 contains 39m39 bgbak b 39m39a 9 b contains 0 O l m Arrays are dimensioned as necessary a special declaration for sparse arrays to save on storage is available Predimensioning large multidimension arrays AZeroslOOlOO or oneslOOlOO will speed things up A scalar is a 1X1 array or eyelOO F FORTRAN MATLAB Special characters begin a comment anywhere in a line amp continued on the next line range operator for indices A252 subfield designator in a structure begin a comment anywhere in a line also used in formats continued on next line range operator for indices much more commonly used in MATLAB than in F shell escape character gives access to the operating system suppress printing of the result or in matrices means quotnext rowquot Math ops l e r A array left divide 39 complextranspose r39 transpose rt r r A elementbyelementoperations Logical ops andl tori notl leqvl ineqvl 5c and l or not comparisons element by element Relational ops lt gt lt gt AltBlorlCB lt gt lt gt comparisons element by element AltB l CB all A Le are all in a column if A is 2D true any A Le are any in a column true all all A to get a scalar from a 2D or 3D array To checkA B when they are arrays use lsequal AB because C AB returns an array with 1 s where elements of A elements of B Character ops concatenate two strings quotHarrlquotquotsonburgquot E quotHarrisonburgquot use reads and writes to convert strings tofrom numbers chargvarquotMay l0 l994quot readunltchargvarfmt monthdayyear where day and year are integer variables and month and charvar are character variables 39Harrl39 39sonburg39 yields the string array 39Harrlsonburg39 numZStr lnt2str and str2num convertnumberstofrom strings F FORTRAN MATLAB Flow of Control if altb then statements else if ac then statements else statements end if OR if condition statement if altb statements elseif ac statements else statements end do 13ll startendinc statements including possible end do exit or cycle OR do lllO statements do Jl20 statements end do name2 end do namel the names are optional but are useful to allow the compiler to check consistency namel name2 for i 3211 end statements include possible use of break or continue start inc end Where possible for statements should be replaced with their matrix equivalents meshgrid 39 be usefulwhen vectorizing for loops that are nested 2 or 3 deep lJK meshgridlimaxljmaxlkmax do construct with no loop control exmpl do if b exit exmpl statements end do exmpl if statement placed where necessary while logical expression is true statements end cycle loopname statement passes control to the next iteration of the do loop named or inner most current loop ski in an remainin statements in the body of the loop exit loopname estnamedloop continue statement passes control to the next iteration of the inner most for or while loop in which it appears skipping any remaining statements in the body of the loop break exits current inner most loop F FORTRAN MATLAB expres sion integer or chararacter exp one or more values sep by commas select case case 06 statements case 1 5710 statements case default statements end select ranges of values are allowed If none of the above matched only one statement executes switch expression SCdarOfs Mg case 0 statements Case 12 statements otherwise statements curly braces so a cell array ranges like 24 are not allowed end only one statement executes to execute statements until an error occurs and then respond to the error try m catch m end Working with arrays constructing arrays xl23456 Ylli4 1H2 21 4 aIl2 Assuming x is dimension6 1282 implied do loop aIl34 usepartsofa realdimension23 AO O A reshapex23 123intoprow 456 in bottom row 6 8 yItA2 a112 aIl34H eros23 msoavaw onesmn reshapex23 1 2 7 43 enter a 2x2 matrix C C is a 4x2 matrix C above C interchanges rows 2 and 3 X I Z A eyen A C B D l Bl 3 2 4 array assignment ab only if b is a scalar or a and b are the same size a1324 b1313 worksok even if a and b are different sizes ab a becomes the same size as b al324 bl3l3 worksok multiply divide CmatmulAB C where the dimensions are Akm Bmn and Ckn C AB is the same as CAB391 C AB is the same as CA391B A kB elemental functions operate on arrays element by element functions can be written using element by element operators F FORTRAN MATLAB where altO bea a and b must have the same dimensions elsewhere condition ba endwhere also see the forall construct make b the same size as a k is a column array of 1D indices where the condition is true a and b are treated as 1D arrays in column order even though they may be 2 or 3 dimensional o bzerossizea kfindalt0 blk4ak kfindagt0 blkak o0 o o0 o0 o0 allocatable arrays real dimension allocatable biggarray allocatebiggarraynln2 staterr4status deallocatebig4arrayother4big7array transparent to the user except for deaocation clear name to clear a variable from the workspace to save space Complicated data types user defined types public class integer year quarter character len 30 end type class type class english geometry english instructor quotSimmsquot geometry class l996thirdquotJonesquot tYPe instructor User defined operations on defined types are allowed See references cell arrays provide storage for dissimilar kinds of data c A sumA prodprodA note outer curly braces c i l retrieves A note not c i l 2 retrieves the 2nd element of A structures similar to cell arrays store the data in named fields 8 name 39Ed Plum39 8 score 83 82struct39name3939Jerry May39 NMs 2 name NM 9 Jerry May aSlscore a98370 39score3970 9 o 9 o Programs and sub programs program test statements contains various subroutine or function defs end program test Subroutines and functions defined after a contains share the variables declared in the program or module script a list of commands in a file named scriptnamem that operates on or generates new variables in the workspace Executed with gtgt scriptgname at the command prompt OR gtgtfunction nogingout a function with zero arguments OR gtgtfunction rlr2 f4nameAtol Seenextpagd The script couldwould effect the variables in the workspace while functions would not F FORTRAN MATLAB pure function f4nameatol real intentintol real r characterlen statements r somegvalue end function fgname resultr intentin a All function input arguments m be intentin character inputs M use len There is only one result variable but it can be an array or user defined type fnameargs is used in the calling routine as if it were one of the built in functions A return statement can be used to force early temination recursive functions and subroutines may also be defined using it in place of pure pure subroutine sampleabc characterlen intentina real dimension O intentinout b integer intentout c integer save callgcount0 callgcountcall4countl statements end subroutine sample Note a dummy dimension 0 means the index starts at 0 saved betw calls In the calling routine use call samplepersongnamepurchasesnumber pure functions and subroutines have no side effects other than the result values for functions All args must be intentin Declaring a procedure as pure helps compilers optimize the code Why allow pure subroutines Not obvious O tional ar uments are allowed See reference for details function rlr2 f4nameAtol or rfnameAJoD A and tol are input arguments rl and r2 are the output args The first contiguous set of comment lines is what is printed out after gtgt help fgname o0 o0 o0 o0 Functions are Mfiles that can accept input arguments and return output arguments The name of the Mfile and of the function must be the same arguments are passed by value so no FORTRAN tricks equivalent to intentinout Variables defined inside the function are local to the function unless declared global in all functions using it global broadlygusedgvariable Variables that you want to remain in memory from one function call to the next should be declared persistent persistent longglastinggvariable No end statement is required or even wanted return can be used to terminate a function early nargin and nargout values are available subfunctions are functions that are defined within the same m file as their parent generally after the parent in the parent s file but see also nested and anonymous functions added in V 7 Because they have no separate mfile they cannot be called by other functions Other than that they are identical with functions and their first line starts in exactly the same way function outgarg fungnamein4args also see private functions for when you want to use the same function name for different purposes Optional ar uments are allowed See reference for details F FORTRAN MATLAB Standard unit IO no redirection of keyboard input and screen output print quotxquotx I printto screen or redirected file with default format displayx is the same as just typing x at gtgt dispx prints X without the initial x on the previous line To copy the F code you need to assemble the string to be printed disp 39X39 num2strx OR see fprintf below print quot t7a5f5ties12t3 3 i4 quot amp quottimequot X scignotation n1 n2 n3 this tabs to the 7th column prints a string a fixed point a sci notation goes to the next line and then prints 3 integers the format quot stuff quot can be a character parameter as characterlen8 parameter fmtquot f5 t 3 quot print fmt X writeunitfmt is identical to print print 95 sends the current figure to the default printer print AdpsCZ filename sends the current fig to filename as level 2 color postscript There are numerous other options print ef2 myfile print ef3 eappend myfile first prints figure 2 to myfile and then appends figure 3 use printopt to set defaults saveas gcf 39file 39 39fig39 save current figure as fig open filetfig reloads the above figure export in the file menu of the figure is used to save the figure if you want to later import the figure into a word processor read x y read from keyboard or redirected file with default format readunitfmt is identical to read input for user input from the keyboard n input 39promptgstring39 for numeric input name input 39promptgstring39 39 s 39 for a string File IO openunit fid filequotnamequot statusquotstatquot actionquotactquot lfid is an integer expression quotnamequot is a legal file name stat one of old new replace l quotactquot one of quotreadquot quotwritequot quotreadwritequot closeunitfid statusquotkee or delete fid e fopen39filename39permission permission 39r39 read 39w39 write file if it already exists 39a39 status fclosefid status fclose39all39 erase old append printunitfidfmtquot3f52 es123quot a b c d l the fid was connected to a file using an open l a string variable or parameter can hold the format example format codes integer i4 fixed point f51 expon e123 sci es123 character a20 tabto20 t20 tabright6 tr6 tableft2 tl2 logical l2 newline fprintf formatted print to a file count fprintffid formatA t t t format 396c 6t2f 12t8g n39 would have 6 characters 6 spaces for a 2 decimal place number 12 spaces for a general f or e exponential number followed by a newline fprintf x 5t2f39x no fid 9 goes to screen F FORTRAN MATLAB readunitfidfmtstring4var OR readunitfidfmtxyZ l the d was connected to a le using an open ainllO s load data txt39 loads simple data file fscanf formatted scan from a file A fscanffidformat OR Acount fscanffidformatsize format 39g g39 reads two floating point numbers per line read n elements size inf read to end of file size 2 inf read into a 2 row array o size n o use unformated direct files for binary read and write fread and fwrite are binary read and writet advantage is compactness and speed but not as portable saving and loading workspace variables myfile saves all workspace vars to myfilemat save myfile varlvar2 savesju those load myfile reads in variables already saved in a mat file load myfile x Y reads in just those also see saveas open S ave Common builtin functions abs max min floor ceiling exp log sgrt sin cos tan asin acos atan sinh cosh tanh conj aimag modulo randomgnumber numbers 091 abs max min floor ceiling exp log sgrt sin cos tan asin acos atan sinh cosh tanh conj imag real mod rand randn int2str gtgt help elfun or elmat or datafun to get a longer list Passing procedure names as parameters Procedure names passed as arguments need an interface inside the called procedure can t pass bui in functions subroutine testginterfacefxa interface function fx resultf4result real intentin x real fgresult end function f a is used in the subroutine but not end interface in f so it isn t in the interface other declarations and statements pass functions to other functions using a function handle fghandle functiongname y anothergfunf4handlex then inside quotanotherfunquot use the feval statement function r anothergfunfx r fevalfx of course the passed function may have more than one arg F FORTRAN MATLAB Stuff that is in one program but not the other Modules Graphics Private modules are the norm module mygmod42 use mygmodgl private If other modules are used they must be followed by private next is a list of procedure names contained in the module declared publicprivate available outside the module public funcgl subAA private func42 next is a list of declarations of variables available to all procedures in the module public makes the variable available outside the module as well real public parameter integer nln2n3 pi3tl4l59265358 contains function rlfuncglab might define local variables statements end function funcgl function r2func42c statements end function func42 subroutine sub4AXy statements end subroutine subgA end module mygmod42 plot 2D plotXlyl39ke39x2y239gv39 2 curves with 2 different line styles Line styles set by i c m y r 9 cyan magenta yellow red g b w k 9 green blue white and black 2 e 44 e 9 soli dash dot dashdot 3 o t x 9 obvious point markers s d A v gt lt 9 solid square diamond or4 triangles Modify the graph with hold on if you want to plot the next graph on top of this one legend39curvel3939curve239 axisxmin xmax ymin ymaxl or axis square or axis equal grid onoff Xlabel39time39 ylabelstring4name4var title39Graph of the sine function39 text5939itNote the odd symmetry 39 position the text starting at x5 y9 figure n pick the n hfigure subplot m n p m x n plots pick the pth clf clear the current figure other 2D graphs the workjust like plot loglog semilogx semilogy polar dsoavaHaMeiezplot39fgname39min max and ezpolar


Buy Material

Are you sure you want to buy this material for

25 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

Why people love StudySoup

Bentley McCaw University of Florida

"I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"

Kyle Maynard Purdue

"When you're taking detailed notes and trying to help everyone else out in the class, it really helps you learn and understand the I made $280 on my first study guide!"

Jim McGreen Ohio University

"Knowing I can count on the Elite Notetaker in my class allows me to focus on what the professor is saying instead of just scribbling notes the whole time and falling behind."


"Their 'Elite Notetakers' are making over $1,200/month in sales by creating high quality content that helps their classmates in a time of need."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.