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

  • Context: MATLAB 
  • Thread starter Thread starter phillyj
  • Start date Start date
  • Tags Tags
    Matlab
Click For Summary
SUMMARY

The discussion focuses on summing the function 2^n from 0 to n using MATLAB. The user initially struggled with the sum() function but found a solution using a one-liner: sum(2.^(0:n)). This approach efficiently calculates the sum for any specified value of n, demonstrating MATLAB's capability for concise mathematical operations.

PREREQUISITES
  • Basic understanding of MATLAB programming
  • Familiarity with MATLAB's vectorized operations
  • Knowledge of exponentiation in programming
  • Understanding of loops and summation concepts
NEXT STEPS
  • Explore MATLAB's array operations for efficient calculations
  • Learn about MATLAB's built-in functions for mathematical computations
  • Investigate the use of anonymous functions in MATLAB
  • Study optimization techniques for MATLAB code performance
USEFUL FOR

Beginners in MATLAB programming, educators teaching mathematical concepts using MATLAB, and anyone interested in efficient coding practices for summation tasks.

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
4K
  • · Replies 2 ·
Replies
2
Views
4K
  • · Replies 10 ·
Replies
10
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 9 ·
Replies
9
Views
4K
  • · Replies 2 ·
Replies
2
Views
4K
  • · Replies 22 ·
Replies
22
Views
4K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 1 ·
Replies
1
Views
2K