# How do i replicate power function? in MATLAB

## Homework Statement

need to do a power function of any number to any power WITHOUT using the power key

aka i need to replicate the power function using only loops and multiplication

for example, compute 5 to the third power by doing 5*5*5 not 5^3

but i don't know how to tell matlab to multiply a number by itself n times

for loops

## The Attempt at a Solution

Code:
num = input(' value? ')
n = input( ' power? ')
for num = 1:n
num = num*num;
end
disp(num)

## Answers and Replies

Related Engineering and Comp Sci Homework Help News on Phys.org
Mark44
Mentor
Try this. Note that it is a bad idea to use the same variable for both input and as a loop counter. This is why I changed the loop counter variable to i.
Code:
num = input(' value? ')
n = input( ' power? ')
product = 1
for i = 1:n
product = product*num;
end
disp(product)
Using your example numbers of num = 5 and n = 3 (to get 53), you get these values for product:
product = 1 (before start of loop)
product = 5 (when i = 1)
product = 25 (when i = 2)
product = 125 (when i = 3)

CEL
a^b = exp(b*log(a))

Mark44
Mentor
a^b = exp(b*log(a))
True (sort of), but not relevant to this problem. log on the right side above should be ln, the natural log.

Emphasis added.
physizl said:
aka i need to replicate the power function using only loops and multiplication

CEL
True (sort of), but not relevant to this problem. log on the right side above should be ln, the natural log.

Emphasis added.
In Matlab log is the natural logarithm. The base 10 logarithm is log10.
Using loops and multiplication you can only calculate powers of natural integer exponents.

Mark44
Mentor
The OP seems to be giving conflicting information about the problem - using loops and multiplication (which is fine for pos. integer exponents) vs. raising a number to any power.