Translate code matlab to python numpy
<p>I don't understand about matlab programming, I just understand coding in python...</p>

<p><img src="http://i.stack.imgur.com/ww2zr.jpg" alt="here my matrix want to solve "></p>

<h3>Matlab Code:</h3>

<pre><code> x = ones(3,1).
con = [0.505868045540458,0.523598775598299].
series = [1,2,3] 
for j = 1:2 
   #here stuck to translate Python code#
   x = [x cos(con(j)*series)' sin(con(j)*series)'];
end
</code></pre>

<h3>Result :</h3>

<pre><code>1.0000    0.8748    0.4846    0.8660    0.5000
1.0000    0.5304    0.8478    0.5000    0.8660
1.0000    0.0532    0.9986   -0.0000    1.0000
</code></pre>

<p>Anyone help me please, how to solve this problem...
Regards!</p>

<p>Here's a solution that entirely removes the loop which resizes the array, which <strong>for large <code>len(con)</code></strong> should make this more efficient than the matlab solution , and by association hpaulj's direct translation - this is linear in len(con) rather than quadratic.</p>

<pre><code>import numpy as np

# declare the arrays
con = np.array([0.505868045540458, 0.523598775598299])
series = np.array([1,2,3])

# use broadcasting to generate trig_arg[i,j] = series[i]*con[j]
trig_arg = series[:,np.newaxis] * con

# Add another dimension that is either cos or sin
trig_elems = np.stack([np.cos(trig_arg), np.sin(trig_arg)], axis=-1)

# flatten out the last two dimensions
all_but_ones = trig_elems.reshape(trig_elems.shape[:-2] + (-1,))

# and add the first column of ones
result = np.concatenate([
    np.ones(series.shape)[:,np.newaxis],
    all_but_ones
], axis=-1)
</code></pre>

<p>Looking at each step along the way:</p>

<pre><code># configure numpy output to make it easier to see what's happening
&gt;&gt;&gt; np.set_printoptions(suppress=True, precision=4)
&gt;&gt;&gt; trig_arg
array([[ 0.5059,  0.5236],
       [ 1.0117,  1.0472],
       [ 1.5176,  1.5708]])
&gt;&gt;&gt; trig_elems
array([[[ 0.8748,  0.4846],
        [ 0.866 ,  0.5   ]],

       [[ 0.5304,  0.8478],
        [ 0.5   ,  0.866 ]],

       [[ 0.0532,  0.9986],
        [-0.    ,  1.    ]]])

&gt;&gt;&gt; all_but_ones
array([[ 0.8748,  0.4846,  0.866 ,  0.5   ],
       [ 0.5304,  0.8478,  0.5   ,  0.866 ],
       [ 0.0532,  0.9986, -0.    ,  1.    ]])

&gt;&gt;&gt; result
array([[ 1.    ,  0.8748,  0.4846,  0.866 ,  0.5   ],
       [ 1.    ,  0.5304,  0.8478,  0.5   ,  0.866 ],
       [ 1.    ,  0.0532,  0.9986, -0.    ,  1.    ]])
</code></pre>

<p>â<code>np.stack</code> is relatively new, but can be emulated with <code>np.concatenate</code> and some <code>np.newaxis</code> slicing. Or you can just go into the numpy source code and copy the new implementation of <code>stack</code> into your project if you're stuck with an older version.</p>

python matlab numpy math computer-science