python - Overcoming dimension errors with matrix multiplication? -
i'd multiply 2 matrices (to clear want in linear algebra meaning of word, i.e., if want further clarification of mean see wikipedia article) i've tried a * b
(which got following matlab numpy guide @ scipy wiki) when a
had dimensions of (n-1)x(n-1) , b
had dimensions of (n-1)x(n+1) gave out valueerror (where n=100
):
valueerror: operands not broadcast shapes (99,99) (99,101)
i tried np.dot(a,b)
in case unintentionally using array (ps. case, have few np.asarray commands vectors built , b from. how convert them matrices?) , not matrix , got same result.
this code in full (granted , b replaced np.diag(xasub)
, np.sin...
, respectively , on d2tsub
line)
import numpy np import scipy.special sp n = 100 n = range(0,n+1) xmin = -10 xmax = 5 pi = np.pi x = np.cos(np.multiply(pi / float(n), n)) xa = np.asarray(x) xasub = xa[1:n] xc = (1+xa)*(xmax-xmin) / float(2) xcsub = xc[1:n] na = np.asarray(n) nd = np.transpose(na) t = np.cos(np.outer(np.arccos(xa),nd)) tsub = t[1:-1] numpy import linalg la dt = np.sin(np.outer(np.arccos(xa),nd))*na dtsub = dt[1:-1] d2tsub = np.diag(np.power((xasub*xasub-1),-1)) * (tsub*nd - np.diag(xasub) * np.sin(np.outer(np.arccos(xasub),nd))) * nd
i've replicated matlab code with:
n = 100. n = np.arange(n+1).reshape(1,-1) x = np.cos(np.pi*n/n).t xsub = x[1:-1,:] t = np.cos(np.arccos(x)*n) # broadcasted outer product tsub = t[1:-1,:] dt = np.dot(np.sin(np.arccos(x)*n), np.diag(n.flat)) # np.diag needs 1d input generate 2d array # case of matrix multiplication, np.dot array # * np.matrix
continuing
temp = np.dot(np.diag(xsub.flat), np.sin(np.arccos(xsub)*n)) temp = np.dot(tsub, np.diag(n.flat)) - temp temp = np.dot(temp, np.diag(n.flat)) d2tsub = np.dot(np.diag((1/np.sqrt(1-xsub**2)).flat), temp))
messy, runs , generates matching value. use of np.matrix
versions of these arrays might simplify appearance, cleaning repeated np.diag(...flat)
.
for rest of d2t
, vstack
pretty literal translation.
d2t1 = ((-1)**n) * (n**2-1) * (n**2)/3 d2t2 = (n**2-1) * (n**2)/3 d2t = np.vstack([d2t1, d2tsub, d2t2])
last step matrix divide. matlab has 2 versions:
d2 = np.linalg.solve(t, d2t) # matlab t\d2t d2 = np.linalg.solve(t.t, d2t.t).t # matlab d2t/t
i worked out last equivalence octave docs y/x
, x\y
.
this literal translation. i'm not trying understand going on, or make idiomatic numpy
.
a partial simplification. no need matrix products use diagonal matrices. simple (broadcasted) element multiplication enough.
n = np.arange(n+1) x = np.cos(np.pi*n/n)[:,none] xn = np.arccos(x)*n t = np.cos(xn) dt = np.sin(xn)*n xsub = x[1:-1,:] d2tsub = ((1-xsub**2)**(-.5)) * (t[1:-1,:] * n - xsub * np.sin(xn[1:-1,:])) d2t2 = (n**2-1) * (n**2)/3 d2t1 = ((-1)**n) * d2t2
you replace lot of diag(n)*
in matlab n.*
example
dt = n.*sin(acos(x)*n); # equals dt = sin(acos(x)*n)*diag(n);
however, tested in octave has broadcasting. i'm not sure matlab stands in regard.
Comments
Post a Comment