How do i replicate power function? in MATLAB

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
5 replies · 8K views
physizl
Messages
9
Reaction score
0

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

Homework Equations



for loops


The Attempt at a Solution



Code:
num = input(' value? ')
n = input( ' power? ')
for num = 1:n
    num = num*num;
end
disp(num)
 
Physics news on Phys.org
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 said:
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
 
Mark44 said:
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.
 
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.