0

I'm new to Python programming. Coming from a MATLAB background. I'm looking something similar to symsum function from MATLAB in Python.

I have my array,

a = np.linspace([0,3.14])

I want to sum

sin(2*i*a) where i ranges from 1 to 20

and then plot the results between a and y

I tried the following

y = nsum(lambda i: np.sin(2*i*a), [0,20])

I'm stuck at this point.

Edit. The MATLAB equivalent would be

a = linspace(0,pi) syms i y=double(symsum(sin(2*i*a),i,0,20)

Venus8588
  • 15
  • 6
  • `[0, 20]` produces a two-element list that contains elements 0 and 20. To get a list of numbers from 1 to 20 use `range(1, 21)` (remember that in Python things are 0-based). did you try just using the Python `sum` function? Are you sure that you want to compute the sum? Since you want to plot `a` vs. `y` it seems maybe you want to just evaluate at each element in `a`? – Daniel Junglas Mar 30 '20 at 05:11
  • It might help if you showed working MATLAB/Octave code. Then I could try to replicate it with `numpy`. – hpaulj Mar 30 '20 at 06:27
  • why mpmath tag? – hpaulj Mar 30 '20 at 07:01
  • @Daniel Junglas yes. I want to just evaluate at each element in `a`. – Venus8588 Mar 30 '20 at 13:27
  • @hpaulj I used `mpmath` because of the `nsum`. I've edited the question to include the equivalent MATLAB code. – Venus8588 Mar 30 '20 at 15:18
  • `mpmath` is often used with `sympy`, but rarely with `numpy`. So the source of `nsum` was not obvious. – hpaulj Mar 30 '20 at 16:04
  • @hpaulj I really appreciate it. This is my Day 1 in Python world. – Venus8588 Mar 30 '20 at 16:16

1 Answers1

0

edit

Looks like symsum is part of a symbolics package (in MATLAB and Octave). sympy is the Python symbolics package. Its integration with numpy is looser.

===

Here's a guess as to what you are trying to do:

A range of a values:

In [180]: a = np.linspace(0, np.pi, 100)                                                     

Outer product with (0,1,2,3,4) (uses broadcasting)

In [181]: x = np.arange(5)[:,None]*a          

Sum the sin values, and plot:

In [182]: y = np.sin(2*x).sum(axis=0)                                                        
In [184]: plt.plot(a,y)                                                                      

sum of 5 sins

hpaulj
  • 221,503
  • 14
  • 230
  • 353