How can I adapt a summation function (see below) with a for loop to create a "x to the power of n" function without using the "^" operator?

5 views (last 30 days)
Hey All!
Below is a simple "sum" function.
function [answer] = sum (n)
answer = 0;
for i = 1:n
answer = answer + i;
end
end
My question is - how can i turn/adapt this sum function into x^n function, without using the "^" operator and only using the definiton of the exponent i.e. x^n = x x x x x x x (n times)
Thanks and i hope i formulatedt this question properly!
Rohit
  3 Comments
Rohit Kumar Sil
Rohit Kumar Sil on 4 Dec 2018
Edited: per isakson on 4 Dec 2018
It's more like a practice question from uni.
Well i tried to start out by following a similar path to when i figured out the intial sum function, which basically displayed Σ(i) from i =1 to 100.
And now i was trying to figure out how i could adapt the aforementioned formula to design a for loop for a basic x^n exponential function.
I have this so far ( no idea if its ok because it's the first time I'm using 2 independant variables in the for loop i.e. n and x) which is really not alot...
function [answer] = exponent(x,n)
x=0; %initialization
n=0; %initialization
for i = 0:n
...
;(

Sign in to comment.

Accepted Answer

madhan ravi
madhan ravi on 4 Dec 2018
Edited: madhan ravi on 4 Dec 2018
I mean is the loop necessary?
n=4;
cumsum(repmat(2,1,n)) % 2 is x here
if you still insist:
answer = sum1(x,n) %function call
function answer = sum1(x,n) %changed sum to sum1 because it will contradict with the inbuilt function
answer=zeros(1,n); % pre-allocation
answer(1) = x;
for i = 2:n
answer(i)=answer(i-1)*answer(1);
end
answer;
end
  3 Comments
madhan ravi
madhan ravi on 4 Dec 2018
Edited: madhan ravi on 4 Dec 2018
Anytime :) , make sure to accept the answer if it helped you , it defines the first element of the array learn about array indexing in matlab

Sign in to comment.

More Answers (1)

per isakson
per isakson on 4 Dec 2018
Try
function [answer] = raised(x,n)
answer = 1;
for ii = 1:n
answer = answer * x;
end
end
and test
>> raised( 3, 4 )
ans =
81

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!