1
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
MPW
  • 43,638
joke
  • 41
  • you should learn how to write the simplest function first. You are returning a matrix as value. Try power = 1 instead. – Memming Feb 24 '14 at 00:22
  • power is supposed to be a scalar, but when you write power(a,n) you are trying to index into it as if it were an array. – littleO Feb 24 '14 at 00:25

1 Answers1

1

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
Daryl
  • 5,598