Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Post a new message in narrative form (i.e. no bullet points) that addresses the

ID: 3845213 • Letter: P

Question

Post a new message in narrative form (i.e. no bullet points) that addresses the following questions: In your own words, explain the concept of variable scope. Include one or more code fragments that you write for this discussion post to help illustrate your case. Clearly mark as appropriate any code fragments as either "script" code or "function" code, and use comments in your code to note the locality of each variable at least the first time the variable appears in the script or function. If a variable is local in scope, be sure to notate what the variable is local to (i.e. the script, a particular function, etc.). Your code for this discussion post should include at least two different local variables, and at least one global variable. Compare and contrast separate function files with anonymous functions. In your opinion, when may it be best to use one over the other? Can you use them interchangeably in all circumstances?

Explanation / Answer

Example:

The scope of a variable is the region where the variable is accesseable. If we acces a variable outside the scope of the variable, we mignt be delaing with some runtime errors

x=input('Enter number');
if mod(x,2) == 0
    y = 'even';
else
    y - 'odd'
end
disp(y) %error: 'y' undefined near line 5 column 5
%error: called from   
%demo.m at line 5 column 7

Solution
x=input('Enter number');
y = '';
if mod(x,2) == 0
    y = 'even';
else
    y - 'odd'
end
disp(y) %in the previous case the scope of y was limited within the if blocks, and it was not visible to the disp function

Example 2

function y = oddEven(x)
y = ''
if mod(x,2) == 0
    y = 'even';
else
    y - 'odd'
end
end

oddeven(5)
printf("%s",y) %error: 'y' undefined near line 5 column 5                                                                                                                                %error: called from   
%demo.m at line 11 column 13

y is a local variable and cannot be used by outside outside the function

b)

Annonymous functions are best when the function returns a value and the function can be execued in 1 line of code. Whereas generic functions are more flexible and can be used with ease. We can consider creation of annonymous function inside a normal function is quite normal, but the inverse is not valid operation.An anonymous function is a function that is not stored in a program file, but is associated with a variable whose data type is function_handle. Anonymous functions can accept inputs and return outputs, just as standard functions do. However, they can contain only a single executable statement.

Example:

function y = evenOdd(x)
   isOdd = @(n) mod(n,2);
   if (isOdd(x))
          return 'Odd'
   else
         return 'even'
end