Recursive function for $a^n$ in matlab

$\begingroup$
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$2

1 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$

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like