MATLAB Getting Started with Matlab: Summing 2n from 0 to n

  • Thread starter Thread starter phillyj
  • Start date Start date
  • Tags Tags
    Matlab
Click For Summary
The discussion focuses on summing the function 2^n from 0 to n in MATLAB. A user initially struggles with using the sum() function correctly. They share a for-loop approach and an alternative method using indexing. Ultimately, they find a concise one-line solution: sum(2.^(0:n)). The thread highlights the simplicity of MATLAB for such calculations.
phillyj
Messages
30
Reaction score
0
Hi, I'm new to matlab.

I'm trying to sum a function similar to 2n from 0 to n where n is specified as a digit and not a list. I am using the sum() function but I don't really know how to get it to work right for this.

Thanks
 
Physics news on Phys.org
Code:
S=0;
n = 10;
for k=0:n;
S = S + 2^k;
end

Or
Code:
ind = 0:1:n;
S = sum(2.^ind);
 
Thanks but I got it. I needed a one-line code like this:

Code:
n = 25
sum(2.^(0:n))
 

Similar threads

  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 10 ·
Replies
10
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 9 ·
Replies
9
Views
3K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 22 ·
Replies
22
Views
4K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 3 ·
Replies
3
Views
5K