I have a Matlab code that I have to convert into python. There is this one operation that I am currently struggling with. I have a Matlab array "edof" which has the dimensions 262144 x 24. I have a second array "dofVector" which has the dimensions 823875 x 1. The operation performed is:
edof = dofVector(edof);
which updates my variable and I get the resulting dimensions of the variable "edof" to be the same as before i.e 262144 x 24 but the values are changed.
I am trying to convert this line of code in numpy but have been unable do so.
edof = dofVector[edof]
I get the following error.
Can someone please help me here?
I am not including the description of the arrays here as this is highly technical and specific to my field.
Thank you!
Numpy indices are zero-based. MATLAB indices are one-based. So if edof is identical between MATLAB and Python up to that step, you'll want to do
edof = dofVector[edof - 1]
I would like to write the following summation in python
The coefficients are given as the following list
cn=[1.2,0.4,0.6]
vn=[1e-6,5e-5,1e-6]
gn=[4.5e3,6.5e3,9e3]
t=np.linspace(0,10,100)
I tried the following
import numpy as np
cn=[1.2,0.4,0.6]
vn=[1e-6,5e-5,1e-6]
gn=[4.5e3,6.5e3,9e3]
t=np.linspace(0,10,100)
yt=np.sum(cn *np.exp(-vn*(t-gn)**2))
but am getting the error
TypeError: bad operand type for unary -: 'list'
I would like to know where am getting it wrong or how to do this task
This run:
import numpy as np
cn=np.array([1.2,0.4,0.6])
vn=np.array([1e-6,5e-5,1e-6])
gn=np.array([4.5e3,6.5e3,9e3])
t=np.linspace(0,10,3)
yt=np.sum(cn * np.exp(-vn * (t - gn)**2))
Transform lists into numpy arrays
Make sure the matrix / array sizes are compatible, (ie. You can't add arrays of different lengths)
Example:
Add int to python list:
cn=[1.2,0.4,0.6]
cn+1
# output: TypeError: can only concatenate list (not "int") to list
Add int to numpy array:
cn=np.array([1.2,0.4,0.6])
cn+1
# output: array([2.2, 1.4, 1.6])
Add numpy arrays with different dimensions:
cn = np.arange(1,3)
t = np.arange(1,100)
cn + t
# output: ValueError: operands could not be broadcast together with shapes (2,) (99,)
Add numpy arrays with the same dimensions:
cn = np.arange(1,3)
t = np.arange(3,5)
cn + t
# output: array([4, 6])
Here is a lazy way of fixing it:
yt=np.sum(cn *np.exp(0-vn*(np.c_[t]-gn)**2), 1)
^ ^------^ ^-^
I've highlighted the changes. The most important change is the np.c_ which does two things:
It converts t to array
It makes t a column vector
1) serves as a "germ" for converting all the other lists to arrays via overloaded arithmetic operators.
Exception: the unary - in front of vn hits vn before it gets the chance to become an array. We put a zero in front the - to make it binary, thereby reducing it's precedence and closing the array coercion chain. This is not the most obvious fix but the one involving the least typing.
2) separates the time dimension from the summation dimension which is likely the correct interpretation. We have to add an eplicit axis argument to the sum which is the 1 we inserted at the very end of the expression.
If found two issues which I fixed but I am not sure is what you intended.
you don't need to convert the list to numpy array because you can perform arithmetic array between ndarray and list which will result ndarray.
Two error found are
1. shape of t was not matching with other arrays
2. you were trying to negate python list which doesn't support it
Also as you haven't put tn in your mathematical expression of summation above so I doubt it you want the length of t to be 3
import numpy as np
cn=[1.2,0.4,0.6]
vn=[1e-6,5e-5,1e-6]
gn=[4.5e3,6.5e3,9e3]
t=np.linspace(0,10,3) # shape of t what 100 and not matching with other arrays
yt=np.sum(cn *np.exp(-(vn*(t-gn)**2))) # -(vn*(t-gn)**2)) wasn't wrapped in brackets
this is my code. but I have the above Error. I searched before but didn't help me to find the answer. What is not correct in this code?
import numpy as np
import math
def sigmoid(x):
s = np.array(None)
for i in x:
np.append(s,(1/(math.exp(-x)+1)))
return s
x = np.array([1, 2, 3])
sigmoid(x)
<ipython-input-31-8e002c20e792> in sigmoid(x)
17 s = np.array(None)`
18 for i in x:
---> 19 np.append(s,(1/(math.exp(-x)+1)))
20 return s
TypeError: only length-1 arrays can be converted to Python scalars
Simply replace math.exp by np.exp. The former is a Python built-in which only understands scalars (hence the error message).
Also note that np.append() returns the result, and does not modify its arguments. So you'll need to assign the result back to s. Also note that repeatedly appending to a NumPy array is an anti-pattern--you should allocate the entire array at the start.
I want to call some python code from MATLAB, in order to do this I need to convert a matrix object to a NumPy ndarray, through the MATLAB function py.numpy.array. However, passing simply the matrix object to the function does not work. At the moment I solved the problem converting the matrix to a cell of cells object, containing the rows of the matrix. For example
function ndarray = convert(mat)
% This conversion fails
ndarray = py.numpy.array(mat)
% This conversion works
cstr = cell(1, size(mat, 1));
for row = 1:size(mat, 1)
cstr(row) = {mat(row, :)};
end
ndarray = py.numpy.array(cstr);
I was wondering if it exists some more efficient solution.
Assuming your array contains double values, the error tells us exactly what we should do:
A = magic(3);
%% Attempt 1:
try
npA = py.numpy.array(A);
% Result:
% Error using py.numpy.array
% Conversion of MATLAB 'double' to Python is only supported for 1-N vectors.
catch
end
%% Attempt 2:
npA = py.numpy.array(A(:).');
% Result: OK!
Then:
>> whos npA
Name Size Bytes Class Attributes
npA 1x1 8 py.numpy.ndarray
Afterwards you can use numpy.reshape to get the original shape back, either directly in MATLAB or in Python.
Actually, using python 2.7 and Matlab R2018b, it worked with simply doing:
pyvar = py.numpy.array(var);
Matlab tells me that if I want to convert the numpy array to Matlab variable, I can just use double(pyvar)
By the way, it didn't worked with python 3.7, neither using an older version of Matlab . I don't know what this means, but I thought this might be helpful
I have two very simple classes: ncut and cluster. Cluster calls a few methods from ncut. You can see the code below. However, when I run cluster.py, I get a TypeError stating that "only length-1 arrays can be converted to Python scalars." I'm pretty new to Python (a few days), and while I've tried to find other similar situations on Stack Overflow, I still can't seem to fix this.
The exact error I get is:
line 62, in cluster D = diag(1/sqrt(rowsum+1e-6)) TypeError: only length-1 arrays can be converted to Python scalars.
At line 62, I have variable D:
# Create Laplacian matrix
rowsum = (sum(abs(S), axis=0))
D = diag(1 / sqrt(rowsum + 1e-6))
L = dot(D, dot(S,D))
# Compute eigenvector of L
U,sigma,V = linalg.svd(L)
I have a feeling that this has something to do with incompatibility stemming from diag or rowsum. Please let me know how I can fix this.
Thanks!