How do i replicate power function? in MATLAB

AI Thread Summary
To replicate the power function in MATLAB without using the power operator, a user needs to utilize loops and multiplication. The correct approach involves initializing a product variable and iterating through a loop to multiply the base number by itself for the specified number of times. An example provided shows how to compute 5 to the power of 3 by updating the product variable in each iteration. It's important to avoid using the same variable for both input and loop counter to prevent confusion. The discussion also clarifies that this method is suitable for positive integer exponents only.
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)
 
a^b = exp(b*log(a))
 
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.
 

Similar threads

Back
Top