Search Results

Search found 1909 results on 77 pages for 'adjacency matrix'.

Page 8/77 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • Numpy ‘smart’ symmetric matrix

    - by Debilski
    Is there a smart and space-efficient symmetric matrix in numpy which automatically fills [j][i] when [i][j] is written to? a = numpy.symmetric((3, 3)) a[0][1] = 1 print a # [[0 1 0], [1 0 0], [0 0 0]] An automatic Hermitian would also be nice, although I won’t need that at the time of writing.

    Read the article

  • A python random function acts differently when assigned to a list or called directly...

    - by Dror Hilman
    I have a python function that randomize a dictionary representing a position specific scoring matrix. for example: mat = { 'A' : [ 0.53, 0.66, 0.67, 0.05, 0.01, 0.86, 0.03, 0.97, 0.33, 0.41, 0.26 ] 'C' : [ 0.14, 0.04, 0.13, 0.92, 0.99, 0.04, 0.94, 0.00, 0.07, 0.23, 0.35 ] 'T' : [ 0.25, 0.07, 0.01, 0.01, 0.00, 0.04, 0.00, 0.03, 0.06, 0.12, 0.14 ] 'G' : [ 0.08, 0.23, 0.20, 0.02, 0.00, 0.06, 0.04, 0.00, 0.54, 0.24, 0.25 ] } The scambling function: def scramble_matrix(matrix, iterations): mat_len = len(matrix["A"]) pos1 = pos2 = 0 for count in range(iterations): pos1,pos2 = random.sample(range(mat_len), 2) #suffle the matrix: for nuc in matrix.keys(): matrix[nuc][pos1],matrix[nuc][pos2] = matrix[nuc][pos2],matrix[nuc][pos1] return matrix def print_matrix(matrix): for nuc in matrix.keys(): print nuc+"[", for count in matrix[nuc]: print "%.2f"%count, print "]" now to the problem... When I try to scramble a matrix directly, It's works fine: print_matrix(mat) print "" print_matrix(scramble_matrix(mat,10)) gives: A[ 0.53 0.66 0.67 0.05 0.01 0.86 0.03 0.97 0.33 0.41 0.26 ] C[ 0.14 0.04 0.13 0.92 0.99 0.04 0.94 0.00 0.07 0.23 0.35 ] T[ 0.25 0.07 0.01 0.01 0.00 0.04 0.00 0.03 0.06 0.12 0.14 ] G[ 0.08 0.23 0.20 0.02 0.00 0.06 0.04 0.00 0.54 0.24 0.25 ] A[ 0.41 0.97 0.03 0.86 0.53 0.66 0.33.05 0.67 0.26 0.01 ] C[ 0.23 0.00 0.94 0.04 0.14 0.04 0.07 0.92 0.13 0.35 0.99 ] T[ 0.12 0.03 0.00 0.04 0.25 0.07 0.06 0.01 0.01 0.14 0.00 ] G[ 0.24 0.00 0.04 0.06 0.08 0.23 0.54 0.02 0.20 0.25 0.00 ] but when I try to assign this scrambling to a list , it does not work!!! ... print_matrix(mat) s=[] for x in range(3): s.append(scramble_matrix(mat,10)) for matrix in s: print "" print_matrix(matrix) result: A[ 0.53 0.66 0.67 0.05 0.01 0.86 0.03 0.97 0.33 0.41 0.26 ] C[ 0.14 0.04 0.13 0.92 0.99 0.04 0.94 0.00 0.07 0.23 0.35 ] T[ 0.25 0.07 0.01 0.01 0.00 0.04 0.00 0.03 0.06 0.12 0.14 ] G[ 0.08 0.23 0.20 0.02 0.00 0.06 0.04 0.00 0.54 0.24 0.25 ] A[ 0.01 0.66 0.97 0.67 0.03 0.05 0.33 0.53 0.26 0.41 0.86 ] C[ 0.99 0.04 0.00 0.13 0.94 0.92 0.07 0.14 0.35 0.23 0.04 ] T[ 0.00 0.07 0.03 0.01 0.00 0.01 0.06 0.25 0.14 0.12 0.04 ] G[ 0.00 0.23 0.00 0.20 0.04 0.02 0.54 0.08 0.25 0.24 0.06 ] A[ 0.01 0.66 0.97 0.67 0.03 0.05 0.33 0.53 0.26 0.41 0.86 ] C[ 0.99 0.04 0.00 0.13 0.94 0.92 0.07 0.14 0.35 0.23 0.04 ] T[ 0.00 0.07 0.03 0.01 0.00 0.01 0.06 0.25 0.14 0.12 0.04 ] G[ 0.00 0.23 0.00 0.20 0.04 0.02 0.54 0.08 0.25 0.24 0.06 ] A[ 0.01 0.66 0.97 0.67 0.03 0.05 0.33 0.53 0.26 0.41 0.86 ] C[ 0.99 0.04 0.00 0.13 0.94 0.92 0.07 0.14 0.35 0.23 0.04 ] T[ 0.00 0.07 0.03 0.01 0.00 0.01 0.06 0.25 0.14 0.12 0.04 ] G[ 0.00 0.23 0.00 0.20 0.04 0.02 0.54 0.08 0.25 0.24 0.06 ] What is the problem??? Why the scrambling do not work after the first time, and all the list filled with the same matrix?!

    Read the article

  • Error at lapack cgesv when matrix is not singular

    - by Jan Malec
    This is my first post. I usually ask classmates for help, but they have a lot of work now and I'm too desperate to figure this out on my own :). I am working on a project for school and I have come to a point where I need to solve a system of linear equations with complex numbers. I have decided to call lapack routine "cgesv" from c++. I use the c++ complex library to work with complex numbers. Problem is, when I call the routine, I get error code "2". From lapack documentation: INFO is INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: if INFO = i, U(i,i) is exactly zero. The factorization has been completed, but the factor U is exactly singular, so the solution could not be computed. Therefore, the element U(2, 2) should be zero, but it is not. This is how I declare the function: void cgesv_( int* N, int* NRHS, std::complex* A, int* lda, int* ipiv, std::complex* B, int* ldb, int* INFO ); This is how I use it: int *IPIV = new int[NA]; int INFO, NRHS = 1; std::complex<double> *aMatrix = new std::complex<double>[NA*NA]; for(int i=0; i<NA; i++){ for(int j=0; j<NA; j++){ aMatrix[j*NA+i] = A[i][j]; } } cgesv_( &NA, &NRHS, aMatrix, &NA, IPIV, B, &NB, &INFO ); And this is how the matrix looks like: (1,-160.85) (0,0.000306796) (0,-0) (0,-0) (0,-0) (0,0.000306796) (1,-40.213) (0,0.000306796) (0,-0) (0,-0) (0,-0) (0,0.000306796) (1,-0.000613592) (0,0.000306796) (0,-0) (0,-0) (0,-0) (0,0.000306796) (1,-40.213) (0,0.000306796) (0,-0) (0,-0) (0,-0) (0,0.000306796) (1,-160.85) I had to split the matrix colums, otherwise it did not format correctly. My first suspicion was that complex is not parsed correctly, but I have used lapack functions with complex numbers before this way. Any ideas?

    Read the article

  • Create a binary indicator matrix in R

    - by Brian Vanover
    I have a list of data indicating attendance to conferences like this: Event Participant ConferenceA John ConferenceA Joe ConferenceA Mary ConferenceB John ConferenceB Ted ConferenceC Jessica I would like to create a binary indicator attendance matrix of the following format: Event John Joe Mary Ted Jessica ConferenceA 1 1 1 0 0 ConferenceB 1 0 0 1 0 ConferenceC 0 0 0 0 1 Is there a way to do this in R? Sorry for the poor formatting.

    Read the article

  • How to remove commas etc form a matrix in python

    - by robert
    say ive got a matrix that looks like: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] how can i make it on seperate lines: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] and then remove commas etc: 0 0 0 0 0 And also to make it blank instead of 0's, so that numbers can be put in later, so in the end it will be like: _ 1 2 _ 1 _ 1 (spaces not underscores) thanks

    Read the article

  • Matrix in python

    - by Werner
    Hi, I am very new to Python, I need to read numbers from a file and store them in a matrix like I would do it in fortran or C; for i for j data[i][j][0]=read(0) data[i][j][1]=read(1) data[i][j][2]=read(2) ... ... How can I do the same in Python? I read a bit but got confused with tuples and similar things If you could point me to a similar example it would be great thanks

    Read the article

  • Differences between matrix implementation in C

    - by tempy
    I created two 2D arrays (matrix) in C in two different ways. I don't understand the difference between the way they're represented in the memory, and the reason why I can't refer to them in the same way: scanf("%d", &intMatrix1[i][j]); //can't refer as &intMatrix1[(i * lines)+j]) scanf("%d", &intMatrix2[(i * lines)+j]); //can't refer as &intMatrix2[i][j]) What is the difference between the ways these two arrays are implemented and why do I have to refer to them differently? How do I refer to an element in each of the arrays in the same way (?????? in my printMatrix function)? int main() { int **intMatrix1; int *intMatrix2; int i, j, lines, columns; lines = 3; columns = 2; /************************* intMatrix1 ****************************/ intMatrix1 = (int **)malloc(lines * sizeof(int *)); for (i = 0; i < lines; ++i) intMatrix1[i] = (int *)malloc(columns * sizeof(int)); for (i = 0; i < lines; ++i) { for (j = 0; j < columns; ++j) { printf("Type a number for intMatrix1[%d][%d]\t", i, j); scanf("%d", &intMatrix1[i][j]); } } /************************* intMatrix2 ****************************/ intMatrix2 = (int *)malloc(lines * columns * sizeof(int)); for (i = 0; i < lines; ++i) { for (j = 0; j < columns; ++j) { printf("Type a number for intMatrix2[%d][%d]\t", i, j); scanf("%d", &intMatrix2[(i * lines)+j]); } } /************** printing intMatrix1 & intMatrix2 ****************/ printf("intMatrix1:\n\n"); printMatrix(*intMatrix1, lines, columns); printf("intMatrix2:\n\n"); printMatrix(intMatrix2, lines, columns); } /************************* printMatrix ****************************/ void printMatrix(int *ptArray, int h, int w) { int i, j; printf("Printing matrix...\n\n\n"); for (i = 0; i < h; ++i) for (j = 0; j < w; ++j) printf("array[%d][%d] ==============> %d\n, i, j, ??????); }

    Read the article

  • How to remove commas etc from a matrix in python

    - by robert
    say ive got a matrix that looks like: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] how can i make it on seperate lines: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] and then remove commas etc: 0 0 0 0 0 And also to make it blank instead of 0's, so that numbers can be put in later, so in the end it will be like: _ 1 2 _ 1 _ 1 (spaces not underscores) thanks

    Read the article

  • A question about matrix manipulation

    - by appi
    Given a 1*N matrix or an array, how do I find the first 4 elements which have the same value and then store the index for those elements? PS: I'm just curious. What if we want to find the first 4 elements whose value differences are within a certain range, say below 2? For example, M=[10,15,14.5,9,15.1,8.5,15.5,9.5], the elements I'm looking for will be 15,14.5,15.1,15.5 and the indices will be 2,3,5,7.

    Read the article

  • Fast matrix transposition in Python

    - by psihodelia
    Is there any fast method to make a transposition of a rectangular 2D matrix in Python (non-involving any library import).? Say, if I have an array X=[[1,2,3], [4,5,6]] I need an array Y which should be a transposed version of X, so Y=[[1,4],[2,5],[3,6]].

    Read the article

  • Java code optimization on matrix windowing computes in more time

    - by rano
    I have a matrix which represents an image and I need to cycle over each pixel and for each one of those I have to compute the sum of all its neighbors, ie the pixels that belong to a window of radius rad centered on the pixel. I came up with three alternatives: The simplest way, the one that recomputes the window for each pixel The more optimized way that uses a queue to store the sums of the window columns and cycling through the columns of the matrix updates this queue by adding a new element and removing the oldes The even more optimized way that does not need to recompute the queue for each row but incrementally adjusts a previously saved one I implemented them in c++ using a queue for the second method and a combination of deques for the third (I need to iterate through their elements without destructing them) and scored their times to see if there was an actual improvement. it appears that the third method is indeed faster. Then I tried to port the code to Java (and I must admit that I'm not very comfortable with it). I used ArrayDeque for the second method and LinkedLists for the third resulting in the third being inefficient in time. Here is the simplest method in C++ (I'm not posting the java version since it is almost identical): void normalWindowing(int mat[][MAX], int cols, int rows, int rad){ int i, j; int h = 0; for (i = 0; i < rows; ++i) { for (j = 0; j < cols; j++) { h = 0; for (int ry =- rad; ry <= rad; ry++) { int y = i + ry; if (y >= 0 && y < rows) { for (int rx =- rad; rx <= rad; rx++) { int x = j + rx; if (x >= 0 && x < cols) { h += mat[y][x]; } } } } } } } Here is the second method (the one optimized through columns) in C++: void opt1Windowing(int mat[][MAX], int cols, int rows, int rad){ int i, j, h, y, col; queue<int>* q = NULL; for (i = 0; i < rows; ++i) { if (q != NULL) delete(q); q = new queue<int>(); h = 0; for (int rx = 0; rx <= rad; rx++) { if (rx < cols) { int mem = 0; for (int ry =- rad; ry <= rad; ry++) { y = i + ry; if (y >= 0 && y < rows) { mem += mat[y][rx]; } } q->push(mem); h += mem; } } for (j = 1; j < cols; j++) { col = j + rad; if (j - rad > 0) { h -= q->front(); q->pop(); } if (j + rad < cols) { int mem = 0; for (int ry =- rad; ry <= rad; ry++) { y = i + ry; if (y >= 0 && y < rows) { mem += mat[y][col]; } } q->push(mem); h += mem; } } } } And here is the Java version: public static void opt1Windowing(int [][] mat, int rad){ int i, j = 0, h, y, col; int cols = mat[0].length; int rows = mat.length; ArrayDeque<Integer> q = null; for (i = 0; i < rows; ++i) { q = new ArrayDeque<Integer>(); h = 0; for (int rx = 0; rx <= rad; rx++) { if (rx < cols) { int mem = 0; for (int ry =- rad; ry <= rad; ry++) { y = i + ry; if (y >= 0 && y < rows) { mem += mat[y][rx]; } } q.addLast(mem); h += mem; } } j = 0; for (j = 1; j < cols; j++) { col = j + rad; if (j - rad > 0) { h -= q.peekFirst(); q.pop(); } if (j + rad < cols) { int mem = 0; for (int ry =- rad; ry <= rad; ry++) { y = i + ry; if (y >= 0 && y < rows) { mem += mat[y][col]; } } q.addLast(mem); h += mem; } } } } I recognize this post will be a wall of text. Here is the third method in C++: void opt2Windowing(int mat[][MAX], int cols, int rows, int rad){ int i = 0; int j = 0; int h = 0; int hh = 0; deque< deque<int> *> * M = new deque< deque<int> *>(); for (int ry = 0; ry <= rad; ry++) { if (ry < rows) { deque<int> * q = new deque<int>(); M->push_back(q); for (int rx = 0; rx <= rad; rx++) { if (rx < cols) { int val = mat[ry][rx]; q->push_back(val); h += val; } } } } deque<int> * C = new deque<int>(M->front()->size()); deque<int> * Q = new deque<int>(M->front()->size()); deque<int> * R = new deque<int>(M->size()); deque< deque<int> *>::iterator mit; deque< deque<int> *>::iterator mstart = M->begin(); deque< deque<int> *>::iterator mend = M->end(); deque<int>::iterator rit; deque<int>::iterator rstart = R->begin(); deque<int>::iterator rend = R->end(); deque<int>::iterator cit; deque<int>::iterator cstart = C->begin(); deque<int>::iterator cend = C->end(); for (mit = mstart, rit = rstart; mit != mend, rit != rend; ++mit, ++rit) { deque<int>::iterator pit; deque<int>::iterator pstart = (* mit)->begin(); deque<int>::iterator pend = (* mit)->end(); for(cit = cstart, pit = pstart; cit != cend && pit != pend; ++cit, ++pit) { (* cit) += (* pit); (* rit) += (* pit); } } for (i = 0; i < rows; ++i) { j = 0; if (i - rad > 0) { deque<int>::iterator cit; deque<int>::iterator cstart = C->begin(); deque<int>::iterator cend = C->end(); deque<int>::iterator pit; deque<int>::iterator pstart = (M->front())->begin(); deque<int>::iterator pend = (M->front())->end(); for(cit = cstart, pit = pstart; cit != cend; ++cit, ++pit) { (* cit) -= (* pit); } deque<int> * k = M->front(); M->pop_front(); delete k; h -= R->front(); R->pop_front(); } int row = i + rad; if (row < rows && i > 0) { deque<int> * newQ = new deque<int>(); M->push_back(newQ); deque<int>::iterator cit; deque<int>::iterator cstart = C->begin(); deque<int>::iterator cend = C->end(); int rx; int tot = 0; for (rx = 0, cit = cstart; rx <= rad; rx++, ++cit) { if (rx < cols) { int val = mat[row][rx]; newQ->push_back(val); (* cit) += val; tot += val; } } R->push_back(tot); h += tot; } hh = h; copy(C->begin(), C->end(), Q->begin()); for (j = 1; j < cols; j++) { int col = j + rad; if (j - rad > 0) { hh -= Q->front(); Q->pop_front(); } if (j + rad < cols) { int val = 0; for (int ry =- rad; ry <= rad; ry++) { int y = i + ry; if (y >= 0 && y < rows) { val += mat[y][col]; } } hh += val; Q->push_back(val); } } } } And finally its Java version: public static void opt2Windowing(int [][] mat, int rad){ int cols = mat[0].length; int rows = mat.length; int i = 0; int j = 0; int h = 0; int hh = 0; LinkedList<LinkedList<Integer>> M = new LinkedList<LinkedList<Integer>>(); for (int ry = 0; ry <= rad; ry++) { if (ry < rows) { LinkedList<Integer> q = new LinkedList<Integer>(); M.addLast(q); for (int rx = 0; rx <= rad; rx++) { if (rx < cols) { int val = mat[ry][rx]; q.addLast(val); h += val; } } } } int firstSize = M.getFirst().size(); int mSize = M.size(); LinkedList<Integer> C = new LinkedList<Integer>(); LinkedList<Integer> Q = null; LinkedList<Integer> R = new LinkedList<Integer>(); for (int k = 0; k < firstSize; k++) { C.add(0); } for (int k = 0; k < mSize; k++) { R.add(0); } ListIterator<LinkedList<Integer>> mit; ListIterator<Integer> rit; ListIterator<Integer> cit; ListIterator<Integer> pit; for (mit = M.listIterator(), rit = R.listIterator(); mit.hasNext();) { Integer r = rit.next(); int rsum = 0; for (cit = C.listIterator(), pit = (mit.next()).listIterator(); cit.hasNext();) { Integer c = cit.next(); Integer p = pit.next(); rsum += p; cit.set(c + p); } rit.set(r + rsum); } for (i = 0; i < rows; ++i) { j = 0; if (i - rad > 0) { for(cit = C.listIterator(), pit = M.getFirst().listIterator(); cit.hasNext();) { Integer c = cit.next(); Integer p = pit.next(); cit.set(c - p); } M.removeFirst(); h -= R.getFirst(); R.removeFirst(); } int row = i + rad; if (row < rows && i > 0) { LinkedList<Integer> newQ = new LinkedList<Integer>(); M.addLast(newQ); int rx; int tot = 0; for (rx = 0, cit = C.listIterator(); rx <= rad; rx++) { if (rx < cols) { Integer c = cit.next(); int val = mat[row][rx]; newQ.addLast(val); cit.set(c + val); tot += val; } } R.addLast(tot); h += tot; } hh = h; Q = new LinkedList<Integer>(); Q.addAll(C); for (j = 1; j < cols; j++) { int col = j + rad; if (j - rad > 0) { hh -= Q.getFirst(); Q.pop(); } if (j + rad < cols) { int val = 0; for (int ry =- rad; ry <= rad; ry++) { int y = i + ry; if (y >= 0 && y < rows) { val += mat[y][col]; } } hh += val; Q.addLast(val); } } } } I guess that most is due to the poor choice of the LinkedList in Java and to the lack of an efficient (not shallow) copy method between two LinkedList. How can I improve the third Java method? Am I doing some conceptual error? As always, any criticisms is welcome. UPDATE Even if it does not solve the issue, using ArrayLists, as being suggested, instead of LinkedList improves the third method. The second one performs still better (but when the number of rows and columns of the matrix is lower than 300 and the window radius is small the first unoptimized method is the fastest in Java)

    Read the article

  • Matrix Pattern Recognition Algorithm

    - by Andres
    I am designing a logic analyzer and I would like to implement some Matrix Algorithm. I have several channels each one represented by a row in the matrix and every element in the column would be the state, for example: Channel 1 1 0 0 1 0 1 1 0 1 Channel 2 1 1 0 1 1 0 0 1 1 Channel 3 0 1 0 1 1 0 1 0 0 Channel 4 0 0 1 0 0 1 0 0 1 I would like to detect a pattern inside my matrix for example, detect if exist and where the sub-matrix or pattern: 1 0 1 1 I think it can be accomplished testing element by element but I think there should be a better way of doing it. Is there any Java API or any way to do it ? If there is a API ARM optimized for NEON instructions would be great also but not mandatory. Thank you very much in advance.

    Read the article

  • Scipy sparse... arrays?

    - by spitzanator
    Hey, folks. So, I'm doing some Kmeans classification using numpy arrays that are quite sparse-- lots and lots of zeroes. I figured that I'd use scipy's 'sparse' package to reduce the storage overhead, but I'm a little confused about how to create arrays, not matrices. I've gone through this tutorial on how to create sparse matrices: http://www.scipy.org/SciPy_Tutorial#head-c60163f2fd2bab79edd94be43682414f18b90df7 To mimic an array, I just create a 1xN matrix, but as you may guess, Asp.dot(Bsp) doesn't quite work because you can't multiply two 1xN matrices. I'd have to transpose each array to Nx1, and that's pretty lame, since I'd be doing it for every dot-product calculation. Next up, I tried to create an NxN matrix where column 1 == row 1 (such that you can multiply two matrices and just take the top-left corner as the dot product), but that turned out to be really inefficient. I'd love to use scipy's sparse package as a magic replacement for numpy's array(), but as yet, I'm not really sure what to do. Any advice? Thank you very much!

    Read the article

  • converting a matrix to a list

    - by andrewj
    Suppose I have a matrix foo as follows: foo <- cbind(c(1,2,3), c(15,16,17)) > foo [,1] [,2] [1,] 1 15 [2,] 2 16 [3,] 3 17 I'd like to turn it into a list that looks like [[1]] [1] 1 15 [[2]] [1] 2 16 [[3]] [1] 3 17 You can do it as follows: lapply(apply(foo, 1, function(x) list(c(x[1], x[2]))), function(y) unlist(y)) I'm interested in an alternative method that isn't as complicated. Note, if you just do apply(foo, 1, function(x) list(c(x[1], x[2]))), it returns a list within a list, which I'm hoping to avoid.

    Read the article

  • MATLAB: Convert two array to a sparse matrix

    - by CziX
    I'm looking for an a command or trick to convert two arrays to a sparse matrix. The two arrays contain x-values and y-values, which gives a coordinate in the cartesian coordinate system. I want to group the coordinates, which if the value is between some value on the x-axes and the y-axes. % MATLAB x_i = find(x > 0.1 & x < 0.9); y_i = find(y > 0.4 & y < 0.8); %Then I want to find indicies which are located in both x_i and y_i Is there an easy way to this little trick?

    Read the article

  • Save matrix of double values in OpenCV

    - by Christian
    I have an OpenCV matrix of double (CV_32F) values. I'd like to save it to the disk. I know, I could convert it to an 1-Channel 8-bit IplImage and save it. But that way, I loose precision. Is there a way to save it directly in the 32-bit format, without having to convert it first? It also would be nice, if the resulting file would have an image format, so I can view the result as an image.

    Read the article

  • Computing a normal matrix in conjunction with gluLookAt

    - by Chris Smith
    I have a hand-rolled camera class that converts yaw, pitch, and roll angles into a forward, side, and up vector suitable for calling gluLookAt. Using this camera class I can modify the model-view matrix to move about the 3D world just fine. However, I am having trouble when using this camera class (and associated model-view matrix) when trying to perform directional lighting in my vertex shader. The problem is that the light direction, (0, 1, 0) for example, is relative to where the 'camera is looking' and not the actual world coordinates. (Or is this eye coordinates vs. model coordinates?) I would like the light direction to be unaffected by the camera's viewing direction. For example, when the camera is looking down the Z axis the ground is lit correctly. However, if I point the camera straight at the ground, then it goes dark. This is (I think) because the light direction is parallel with the camera's 'up' vector which is perpendicular with the ground's normal vector. I tried computing the normal matrix without taking the camera's model view into account, but then none of my objects were rotated correctly. Sorry if this sounds vague. I suspect there is a straight forward answer, but I'm not 100% clear on how the normal matrix should be used for transforming vertex normals in my vertex shader. For reference, here is pseudo code for my rendering loop: pMatrix = new Matrix(); pMatrix = makePerspective(...) mvMatrix = new Matrix() camera.apply(mvMatrix); // Calls gluLookAt // Move the object into position. mvMatrix.translatev(position); mvMatrix.rotatef(rotation.x, 1, 0, 0); mvMatrix.rotatef(rotation.y, 0, 1, 0); mvMatrix.rotatef(rotation.z, 0, 0, 1); var nMatrix = new Matrix(); nMatrix.set(mvMatrix.get().getInverse().getTranspose()); // Set vertex shader uniforms. gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, new Float32Array(pMatrix.getFlattened())); gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, new Float32Array(mvMatrix.getFlattened())); gl.uniformMatrix4fv(shaderProgram.nMatrixUniform, false, new Float32Array(nMatrix.getFlattened())); // ... gl.drawElements(gl.TRIANGLES, this.vertexIndexBuffer.numItems, gl.UNSIGNED_SHORT, 0); And the corresponding vertex shader: // Attributes attribute vec3 aVertexPosition; attribute vec4 aVertexColor; attribute vec3 aVertexNormal; // Uniforms uniform mat4 uMVMatrix; uniform mat4 uNMatrix; uniform mat4 uPMatrix; // Varyings varying vec4 vColor; // Constants const vec3 LIGHT_DIRECTION = vec3(0, 1, 0); // Opposite direction of photons. const vec4 AMBIENT_COLOR = vec4 (0.2, 0.2, 0.2, 1.0); float ComputeLighting() { vec4 transformedNormal = vec4(aVertexNormal.xyz, 1.0); transformedNormal = uNMatrix * transformedNormal; float base = dot(normalize(transformedNormal.xyz), normalize(LIGHT_DIRECTION)); return max(base, 0.0); } void main(void) { gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); float lightWeight = ComputeLighting(); vColor = vec4(aVertexColor.xyz * lightWeight, 1.0) + AMBIENT_COLOR; } Note that I am using WebGL, so if the anser is use glFixThisProblem(...) any pointers on how to re-implement that on WebGL if missing would be appreciated.

    Read the article

  • Rotate a 2d matrix to the right

    - by adam
    I want a 2d matrix to rotate to the right, it compiles fine but when I try to the run it freezes. For example I want {{10,20,30},{40,50,60}} to rotate into {{40,10},{50,20},{60,30}} import java.util.*; public class Rotate{ public static int[][] rotate(int[][] m) { int [][] rotateM = new int[m[0].length][m.length]; for (int i= 0; i< m.length; i= i++){ for (int j= 0; j< m[0].length; j= j++){ rotateM[i][j] = m[j][m.length-i-1]; } } return rotateM; } public static void main(String[]args){ int[][]m = {{10,20,30}, {40,50,60}}; System.out.println(Arrays.toString(rotate(m))); } }

    Read the article

  • How attach a model with another model on a specific bone?

    - by Mehdi Bugnard
    I meet a difficulty attached to a model to another model on a "bone" accurate. I searched several forums but no result. I saw that many people have asked the same question but no real result see no response. Thread found : How to attach two XNA models together? How can I attach a model to the bone of another model? http://stackoverflow.com/questions/11391852/attach-model-xna But I think it is possible. Here is my code example attached a "cube" of the hand of my player private void draw_itemActionAttached(Model modelInUse) { Matrix[] Model1TransfoMatrix = new Matrix[this.player.Model.Bones.Count]; this.player.Model.CopyAbsoluteBoneTransformsTo(Model1TransfoMatrix); foreach (ModelMesh mesh in modelInUse.Meshes) { foreach (BasicEffect effect in mesh.Effects) { Matrix model2Transform = Matrix.CreateScale(1f) * Matrix.CreateFromYawPitchRoll(0, 0, 0); effect.World = model2Transform * Model1TransfoMatrix[0]; //root bone index effect.View = arcadia.camera.View; effect.Projection = arcadia.camera.Projection; } mesh.Draw(); } }

    Read the article

  • Matrix multiplication using Matrix Template library (MTL 4)

    - by Lxc
    The program is as following: #include <iostream> #include <boost/numeric/mtl/mtl.hpp> using namespace mtl; int main(int argc, char* argv[]) { dense_vector<double> a(5,1.0); dense_vector<double> b(5,2.0); a * trans(b); } I want to calculate a * trans(b), but there is a compling error :C2893. Will someone help me? Thanks a lot!

    Read the article

  • Matrix loading problems with jbullet and lwjgl

    - by Quintin
    The following code does not load the matrix correctly from jbullet. //box is a RigidBody Transform trans = new Transform(); trans = box.getMotionState().getWorldTransform(trans); float[] matrix = new float[16]; trans.getOpenGLMatrix(matrix); // pass that matrix to OpenGL and render the cube FloatBuffer buffer = ByteBuffer.allocateDirect(4*16).asFloatBuffer().put(matrix); buffer.rewind(); glPushMatrix(); glMultMatrix(buffer); glBegin(GL_POINTS); glVertex3f(0,0,0); glEnd(); glPopMatrix(); the jbullet is configured as so: CollisionConfiguration = new DefaultCollisionConfiguration(); dispatcher = new CollisionDispatcher(collisionConfiguration); Vector3f worldAabbMin = new Vector3f(-10000,-10000,-10000); Vector3f worldAabbMax = new Vector3f(10000,10000,10000); AxisSweep3 overlappingPairCache = new AxisSweep3(worldAabbMin, worldAabbMax); SequentialImpulseConstraintSolver solver = new SequentialImpulseConstraintSolver(); dynamicWorld = new DiscreteDynamicsWorld(dispatcher, overlappingPairCache, solver, collisionConfiguration); dynamicWorld.setGravity(new Vector3f(0,-10,0)); dynamicWorld.getDispatchInfo().allowedCcdPenetration = 0f; CollisionShape groundShape = new BoxShape(new Vector3f(1000.f, 50.f, 1000.f)); Transform groundTransform = new Transform(); groundTransform.setIdentity(); groundTransform.origin.set(new Vector3f(0.f, -60.f, 0.f)); float mass = 0f; Vector3f localInertia = new Vector3f(0, 0, 0); DefaultMotionState myMotionState = new DefaultMotionState(groundTransform); RigidBodyConstructionInfo rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, groundShape, localInertia); RigidBody body = new RigidBody(rbInfo); dynamicWorld.addRigidBody(body); dynamicWorld.clearForces(); Nothing is rendered on the screen. What am I doing wrong?

    Read the article

  • Changing size of a dynamically allocated matrix

    - by user1309174
    Trying to re-size the shape matrix dynamically. This is part of a drawing program where _capacity is the number of shapes drawn on a frame. Get the error in new Shape about _capacity saying expression needs to have a constant value. void ShapeStore::Grow(int minimumCapacity) { _capacity = max (minimumCapacity, 2 * _capacity); if (_capacity) { Shape ***newData = new Shape[_frames][_capacity]; //figure out this int i; for (int k = 0; k < _frames; k++) for (i=0;i<_count;i++) newData[k][i] = _data[k][i]; delete [] _data; _data = newData; } //*/ }

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >