How do i replicate power function? in MATLAB

  • Thread starter physizl
  • Start date
  • #1
9
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)
 

Answers and Replies

  • #2
34,167
5,782
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)
 
  • #3
CEL
656
0
a^b = exp(b*log(a))
 
  • #4
34,167
5,782
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
 
  • #5
CEL
656
0
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.
 
  • #6
34,167
5,782
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.
 

Related Threads on How do i replicate power function? in MATLAB

Replies
0
Views
603
  • Last Post
Replies
2
Views
5K
Replies
2
Views
772
  • Last Post
Replies
5
Views
818
Replies
0
Views
4K
  • Last Post
Replies
1
Views
10K
Replies
0
Views
1K
  • Last Post
Replies
5
Views
1K
Replies
20
Views
989
  • Last Post
Replies
1
Views
2K
Top