A recursive definition of an where a is an integer and n is a non-negative integer follows: a^nif=1 if n = 0 a^n=a*a^(n-1) if n>0 Write a recursive function called mypower, which receives a and n and returns the value of an by implementing the previous definition. Note that the program should not use ^ operator anywhere; this is to be done recursively instead! Test the function. I tried this one but cant work
function power=mypower(a,n) if n==0 power(a,n)=1; else power(a,n)=a*mypower(a,n-1); Thanks
end $\endgroup$21 Answer
$\begingroup$littleO described the problem in the comments. The power variable should be a scalar, but you are treating it as an array. By indexing using a, you will get an error if this is not an integer.
The code should be as follows:
function power = mypower(A,n) % calculate A^n elementwise for a matrix A using the given recursive algorithm if n == 0 power = 1; else power = A.*power(A,n-1); end $\endgroup$