User Tools

Site Tools


gibson:teaching:fall-2014:math445:lecture7-diary

This is an old revision of the document!


A PCRE internal error occured. This might be caused by a faulty plugin

====== Math 445 lecture 7 diary: functions, if statements ====== =====Today's topics===== * functions * ''if'' statements * ''fprintf'': the formatted printing function =====Today's vocabulary===== <code> function if-end fprintf argument return value function definition function declaration function body </code> =====Lecture synopsis===== ====An exceedingly simple function==== The simplest way to define you own function in Matlab is to write it in a text file whose filename matches the function name, with a '.m.' suffix. For example, we can define a ''faren2celsius'' function by creating a text file ''faren2celsius.m'' with the following contents <code matlab> function tempC = faren2celsius(tempF) % convert celsius temperature to farenheit % input argument tempC % output value tempF tempC = 5/9*(tempF-32); end </code> Note the following: -The //function definition// begins with the word ''function'' and ends with ''end''. -The //function declaration// in the first line specifies that the function ''faren2celsius'' will take one //argument// (or input variable) ''tempF'' and produce one //return value// (or output variable) ''tempC''. -The comment lines immediately following the function declaration are a //help string//, which Matlab will print in response to ''help faren2celsius''. -The //body// of the function lies between the help string and the ''end''. Here the function body is a single line of code that calculates ''tempC'' from ''tempF''. ====A few more bells and whistles==== That was an exceedingly simple function. Let's write the inverse function ''celsius2faren'' with a few more bells and whistles. Specifically, let's print a warning message if the input temperature is below absolute zero, -273.15 C. <code matlab> function tempF = celsius2faren(tempC) % convert temperature in Celsius to Farenheit if tempC < -273.15 fprintf('%d C is below -273.15, i.e. absolute zero', tempC); end tempF = 9/5*tempC + 32; end Things to note here:

gibson/teaching/fall-2014/math445/lecture7-diary.1412706888.txt.gz · Last modified: 2014/10/07 11:34 by gibson