Chapter5-3e

# Chapter5-3e - (Cont Global Variables In previous examples...

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

User Defined Functions (Con’t)

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

View Full Document
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.
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:

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

View Full Document
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
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 14

Chapter5-3e - (Cont Global Variables In previous examples...

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

View Full Document
Ask a homework question - tutors are online