Chapter5-3e - UserDefinedFunctions (Cont) Global Variables...

Info iconThis preview shows pages 1–5. Sign up to view the full content.

View Full Document Right Arrow Icon
User Defined Functions (Con’t)
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Global Variables In previous examples, variables were only known in the main program or in a function. Variables in one function are not known in another function or the main program. These types of variables are known as Local Variables Local variables are desirable because: In function a you can use variables x, y, and z. In function b you can use variables x, y, and z. The variables will be independent and are different variables.
Background image of page 2
Global Variables On occasion it is desirable to have a variable in more than one function be the same variable. That is, if we have a variable named a in function x, and a variable named a in function y, we may want a to be the same variable. A variable of this type is referred to as a global variable since it is defined in more than one function. We will first look at an example of a local variable . First we will define function xxx1: f unction z=xxx1(in) z=2*in; fprintf('The value of a is %g\n', a); end % End function xxx1 All this function does is print the value of a (and computes z which is of no concern to us). Next we will write a code segment (a snippet) that assigns a value of a and then calls the function:
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Global Variables a=10; xxx1(25); >> test_xxx1 ??? Undefined function or variable 'a'. Error in ==> xxx1 at 2 fprintf('The value of a is %g\n', a); Error in ==> test_xxx1 at 2 xxx1(25); An error message is generated inside function xxx1 because a is
Background image of page 4
Image of page 5
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 14

Chapter5-3e - UserDefinedFunctions (Cont) Global Variables...

This preview shows document pages 1 - 5. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online