User Tools

Site Tools


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

Math 445 lecture diary: if-elseif-else

Today we'll look at slightly more complex functions, with

  • multiple arguments
  • multiple return values
  • if-elseif-else statements
  • switch statements

Multiple arguments and return values

The declaration of a function f with multiple arguments and multiple return values has general form

function [rtn1, rtn2, rtn3, ...] = f(arg1, arg2, arg3, ...)

if-elseif-else statement

The general form of an if-elseif-else statement is

if condition1
  action1
elseif condition2
  action2
elseif condition3
  action3
else
  action4
end

though of course you can have as many elseif statements as you like.

Example: if-elseif-else and multiple args and return val

Write a Matlab function temp2kcf converts a temperature t in any one of the three units Kelvin, Celsius, or Farenheit, and returns the temperature in all three units. The function should have two arguments, the temperature t and a character units which specifies the units as either K, C, or F and three return values, tK, tC, tF.

Here's a decent solution to the problem using an if-elseif-else statement.

function [tK, tC, tF] = temp2kcf(t, units);
% convert temperature t in units 'C', 'F', or 'K' to all three of those units
 
  % convert input temp to Kelvin
  if units == 'F'
    tK = 5/9*t + 255.37;
  elseif units == 'C'
    tK = t + 273.15;
  elseif units == 'K'
    tK = t;
  else
    fprintf('error: unknown units %c, returning absolute zero\n', units);
    tK = 0;
  end
 
  % convert Kelvin to output temps
  tC = tK - 273.15;
  tF = 9/5*tC + 32;
 
end

switch statement

The above problem is actually better done with a switch statement. Switch statements perform conditional execution based on the value of a variable or an expression. The general form is

switch expression
  case value1
    action1
  case value2
    action2
  case value3
    action3
  otherwise
    action4
end

Here's a solution to the problem using a switch statement.

function [tK, tC, tF] = temp2kcf(t, units);
% convert temperature t in units 'C', 'F', or 'K' to all three of those units
 
  % convert input temp to Kelvin
  switch units
    case 'F'
      tK = 5/9*(t-32) + 273.15;      
    case 'C'
      tK = t + 273.15;
    case 'K'
      tK = t;  
    otherwise
      fprintf('error: unknown units %c, returning absolute zero\n', units);
      tK = 0;
  end
 
  % convert Kelvin to output temps
  tC = tK - 273.15;
  tF = 9/5*tC + 32;
 
end
gibson/teaching/fall-2014/math445/lecture8-diary.txt · Last modified: 2014/10/09 17:01 by gibson