0

I need to understand how I can translate these few lines of MATLAB code. I don't understand how to create a vector n1 of n elements and how to fill it using the same formula as in MATLAB.

Here's the MATLAB code:

nc = 200; ncmax = 600; dx = 0.15e-04; 
r = (dx/2):dx:dx*(ncmax+3); 
n1(1:nc) =(1 ./ (s.*sqrt(2*pi).*r(1:nc))).*exp(-((log(r(1:nc)) - med).^2)./(2*s^2));

I have the following in Python, but n1 is always an empty array of nc elements:

import numpy as np

r =np.arange((dx/2),(dx*(ncmax+3)),dx)
count=1
n1=np.empty(nc)

while (count<nc)

n1[count]=(1/(s*np.sqrt(2*pi)*r[count]))*np.exp(-((np.log(r[count]))-med)**2)/(2*s**2)
count=count+1
hbaderts
  • 14,136
  • 4
  • 41
  • 48

2 Answers2

1

You have a beautifully vectorized solution in MATLAB. One of the main reason for using NumPy is that it also allows for vectorization - so you shouldn't be introducing loops.

As suggested in comments by lucianopaz, there is a guide to NumPy for MATLAB users which explains differences and similarities between the two. It further has a nice list of MATLAB functions and their NumPy equivalents. This may be of great help, when translating MATLAB programs.

Some hints and comments:

  • Use the NumPy versions of all functions, i.e. np.sqrt, np.exp (as you were previously) and np.power (instead of **). These functions can be called in a vectorized fashion, just like in MATLAB.

  • As noticed by @Elisha, you are missing the definitions of s and med, so I'll just assume these are scalars, and set them to 1.

  • Instead of importing math just for the math.pi, you can also use np.pi, which is exactly the same.

  • You are creating a large r vector and only use the first nc elements. Why not make r only of size nc from the start, as shown below?

Resulting NumPy code:

import numpy as np

nc = 200
ncmax = 600
dx = 0.15e-04
s = 1
med = 1

r = np.arange(dx / 2, dx * nc, dx)

n1 = 1 / (s * np.sqrt(2 * np.pi) * r) * \
     np.exp(-np.power(np.log(r) - med, 2) /
            (2 * np.power(s, 2)))
Community
  • 1
  • 1
hbaderts
  • 14,136
  • 4
  • 41
  • 48
  • 1
    Nice answer. I would recommend you add a link to the [numpy for matlab users](https://docs.scipy.org/doc/numpy-dev/user/numpy-for-matlab-users.html) somewhere. It may be a good resource for @Giuseppe to read. – lucianopaz Jan 15 '17 at 23:26
  • Great idea, @lucianopaz - this guide has helped me a lot in the past. – hbaderts Jan 15 '17 at 23:37
0

you have several problems.

  1. pi should be math.pi (after you add import math)
  2. add : to your while line: while (count < nc):
  3. s and med are not defined in the scope you wrote
Elisha
  • 4,811
  • 4
  • 30
  • 46