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)
Show older comments
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
Accepted Answer
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
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
More Answers (1)
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
0 Comments
See Also
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!