Search This Blog

Tuesday, June 15, 2010

options in function variables octave

The following octave code shows how to make functions take different paths depending on a user specified choice. It is a little template that comes in handy once in a while.
$cat options_in_function_variables_01.m
# Author : Kamaraju S. Kusumanchi
# Email : kamaraju at gmail dot com
# Last modified : Tue Jun 15 06:45:15 EDT 2010
function [X] = options_in_function_variables_01(X, choice)

if (strcmp(choice, "square"))
X = X*X;
elseif (strcmp(choice, "unity"))
X = X*1;
elseif (strcmp(choice, "cube"))
X = X*X*X;
printf("choice = %s is not a valid option.\n", choice);
error("please provide a correct choice");

To test it

$octave -qf
octave:1> options_in_function_variables_01(2.2, 'unity')
ans = 2.2000
octave:2> options_in_function_variables_01(2.2, 'square')
ans = 4.8400
octave:3> options_in_function_variables_01(2.2, 'cube')
ans = 10.648
octave:4> 10.648/4.84
ans = 2.2000
octave:5> 4.84/2.2
ans = 2.2000

No comments: