Menu
  • HOME
  • TAGS

Inserting One Row Each Time in a Sequence from Matrix into Another Matrix After Every nth Row in Matlab

arrays,matlab,matrix

Here's another indexing-based approach: n = 10; C = [A; B]; [~, ind] = sort([1:size(A,1) n*(1:size(B,1))+.5]); C = C(ind,:); ...

JavaFX 8 Transform to pitch, yaw and roll rotation angles

matrix,3d,rotation,javafx-8

If you want to get the pitch, yaw and roll angles at any stage after several rotations, you can get them from the transformation matrix of the 3D model. If you have a look at the transformation matrix after several rotations: Transform T = model3D.getLocalToSceneTransform(); System.out.println(T); you'll see something like...

Process a matrix in matlab without for loop

matlab,loops,matrix

Let A be your matrix. If "every n-th row" means rows 1, n+1, 2*n+1,...: result = sqrt(sum(abs(A(1:n:end,:)).^2, 2)); If it simply means "every row": result = sqrt(sum(abs(A).^2, 2)); In either case, if A is real you can remove abs....

How to print the right hemisphere of a square matrix

c++,algorithm,matrix

I think this should work for square matrices: void printHemisphere(int matrix[N][M], int n, int m) { int mid = n / 2; for(int i = 1; i < mid; i++) { for (int j = n - i; j < m; ++j) { std::cout << matrix[i][j] << " "; }...

How to render a matrix of objects to table with combined cells

javascript,html,css,arrays,matrix

Solved with code below var data = [[ {"value": "1"}, {"value": "1"}, {"value": "1"} ], [ {"value": "2"}, {"value": "2"}, {"value": "3"} ], [ {"value": "2"}, {"value": "2"}, {"value": "3"} ], [ {"value": "4"}, {"value": "4"}, {"value": "5"} ]]; function renderCombinedTable(data) { var cell = []; var rows = data.length...

Estimate a matrix of numbers based on known corner values?

python,r,matrix,multidimensional-array,corners

This is not that advanced but may help: import numpy as np import matplotlib.pyplot as plt c1 = 0 # Corner values c2 = 1 c3 = 1 c4 = 4 a=np.linspace(c1, c2, 8) b=np.linspace(c3, c4, 8) c = np.array([np.linspace(i,j,12) for i,j in zip(a,b)]) print np.shape(c) plt.figure() plt.imshow(c) plt.show() ...

Replace the contents of a vector with the values of a matrix

r,matrix,vector,replace

Try match where 'm1' is the matrix match(vector1, m1[,1]) #[1] 2 1 2 3 Or unname(setNames(as.numeric(m1[,2]), m1[,1])[vector1]) #[1] 2 1 2 3 ...

Python equivalent to C++ adjacency list

python,c++,matrix

The Python translation of your code would be: def buildmatrix(): vertices = int(raw_input("Enter # of vertices -> ") matrix = [] for i in range(vertices): matrix.append([]) # alternatively, matrix = [[] for _ in range(vertices)] return vertices, matrix def add_edge(matrix, vertex1, vertex2): matrix[vertex1].append(vertex2) matrix[vertex2].append(vertex1) This works because there's no restriction...

Speeding up Math.NET declaration for symmetric matrices

c#,matrix,mathnet

I think it would be better to split this into two: Firstly, calculate the lower triangle, then in a separate loop assign the values from the lower triangle to the upper triangle. It's likely to be more performant. You might also be able to use Parallel.For for the outer loop...

Removing rows/columns with only one element from a binary matrix

r,matrix

You first want to find which rows and columns are singletons and then check if there are pairs of singletons rows and columns that share an index. Here is a short bit of code to accomplish this task: foo <- matrix(c(0,1,0,...)) singRows <- which(rowSums(foo) == 1) singCols <- which(colSums(foo) ==...

R Pairwise comparisson of matrix columns ignoring empty values

r,matrix,similarity

So the following is the answer from akrun : first changing the blank cells to NA's is.na(my.matrix) <- my.matrix=='' and then removing the NA's for the match.counts similarity.matrix <- matrix(nrow=ncol(my.matrix), ncol=ncol(my.matrix)) for(col in 1:ncol(my.matrix)){ matches <- my.matrix[,col] == my.matrix match.counts <- colSums(matches, na.rm=TRUE) match.counts[col] <- 0 similarity.matrix[,col] <- match.counts }...

R rounds decimal values in matrix when subsetting

r,matrix

Actually, there is nothing wrong here. It is simply a formatting issue. You easily check that values are not affected: > identical(matrixA[2, , drop=F], matrix(c(11903.564, 11385.656), nrow=1) [1] TRUE If want to see more decimal places you can for example use options(digits): > options(digits=10) > matrixA[2, , drop=F] [,1] [,2]...

How to set first column to a constant value of an empty np.zeros numPy matrix?

python,numpy,matrix,modeling

All you have to do is to change head[0][0:] to head[:,0]=16 If you want to change the first row you can just do: head[0,:] = 16 EDIT: Just in case you also wonder how you can change an arbitrary amount of values in an arbitrary row/column: myArray = np.zeros((6,6)) Now...

Python: Change matrix size according to the size of target matrix

python,numpy,matrix

In case the shape of A is (a1,a2), the shape of B is (b1,b2), and you the shape of A' to be (a1,b2) (Like in your example), You can do this: >>>from numpy import matrix,ones >>>A = matrix([[7, 5]]) >>>B = matrix([[2, 0],[0, 0]]) >>>C = ones(A.shape) >>>c_shape = (A.shape[0],B.shape[1])...

Access Struct in C++?

c++,matrix,structure

The program does not make sense. You should either declare an array of type Students or use some other standard container as for example std::vector<Students>. And after the container will be defined you have to enter values for each element. For example const size_t N = 100; Students students[N]; for...

Reversing RotateAxisAngle back to angles

c++,matrix,rotation,geometry,axis

OK, I'm going to take another stab at this. My first answer was for XYZ order of rotations. This answer is for ZYX order, now that I know more about how MathGeoLib works. MathGeoLib represents position vectors as column vectors v = [x y z 1]^T where ^T is the...

function similar to head() for matrix

r,matrix,head,corners

There is a function called peek in a package called futile.matrix. library(futile.matrix) m <- matrix(c(1,3,4,2, 5,10,11,2, 3,42,8,22, 23,15,3,8), ncol = 4) peek(m, 4) From the description of that function: "Peek is a simple utility to conveniently look at a portion of a matrix. This is similar to head and tail...

complexity of generating a sparse matrix

r,matlab,matrix,sparse-matrix

When converting from a full representation of a symmetric matrix to a sparse representation, you will need to scan all the elements on the main diagonal and above (or symmetrically on the main diagonal and below). For an (n x n) matrix matrix this is (n^2+n)/2 entries that need to...

Using a bash script to apply another script to every file in a directory like a matrix

bash,shell,matrix,scripting,file-handling

script_v1.sh: #!/bin/bash compare="/path/to/my/compare_tool" for i in {1..5}; do for j in $(seq $((i+1)) 5); do echo "Comparing $i and $j" compare filename_V000$i.txt filename_V000$j.txt > result_$i_$j.txt done done result_v1: $ > bash script_v1.sh Comparing 1 and 2 Comparing 1 and 3 Comparing 1 and 4 Comparing 1 and 5 Comparing 2...

Apply a function to all column pairs of two matrices in R

r,matrix

You can just do cor cor(metilacion,expression) # A2BP1 A2M A2ML1 A4GALT AAAS #A2BP1 -0.4887051 0.03682951 -0.0404260 0.5795882 -0.03534625 #A2M -0.5909642 0.01572799 -0.1469085 0.3503903 -0.19412101 #A2ML1 0.8006633 0.17242226 0.1294179 -0.5827062 -0.05502329 #A4GALT -0.8036390 0.18066923 -0.2026173 0.6824085 -0.32097886 #AAAS 0.9033514 -0.54378874 0.7694163 -0.7995712 0.13676285 If you need to get the cor of...

Efficiently check if numpy ndarray values are strictly increasing

python,numpy,matrix

>>> import numpy as np >>> a = np.asarray([[1,2,3],[1,5,7],[4,3,6]]) Find the difference between each element. np.diff has an argument that lets you specify the axis to perform the diff >>> np.diff(a) array([[ 1, 1], [ 4, 2], [-1, 3]]) Check to see if each difference is greater than 0. >>>...

In a NxN matrix, what algorithm finds the shortest path between two nodes? [Java]

java,algorithm,matrix

Dijkstra's is the (my) preferred route. It takes in one node and finds the shortest path to all other nodes. Usually for distance between two nodes one would create a check inside Dijkstra's to return when the desired "end" node is reached. In fact, Wikipedia has very nice psuedocode for...

Analytical solution for Linear Regression using Python vs. Julia

python,matrix,julia-lang

A more numerically robust approach in Python, without having to do the matrix algebra yourself is to use numpy.linalg.lstsq to do the regression: In [29]: np.linalg.lstsq(X, y) Out[29]: (array([[ 188.40031942], [ 0.3866255 ], [ -56.13824955], [ -92.9672536 ], [ -3.73781915]]), array([], dtype=float64), 4, array([ 3.08487554e+03, 1.88409728e+01, 1.37100414e+00, 1.97618336e-01])) (Compare the...

Get specific value when trying to access outside of matrix

python,numpy,matrix

You could use a try/except block to handle invalid indices def getItem(a, i, j): try: return a[i,j] except IndexError: return 0 >>> getItem(a, 1, 1) 4 >>> getItem(a, 2, 5) 0 ...

Matlab reshape back into original image

matlab,matrix,multidimensional-array,vectorization,reshape

Just do the reverse of what you used to reshape the original array. The permute commands stay the same (switching the first and second dimension), while the reshape commands go back up to 512 reshaped_i_image = reshape(permute(reshape(permute(sub_images, [2 1 3]), 8, 512, []), [2 1 3]), 512, 512); ...

Unable to convert between 1d and 2d array values

java,arrays,matrix,2d

All arrays start by 0, try this: public static void main(String[] args) { int testSize = 4; Test test = new Test(testSize); for (int i = 0; i < testSize; i++) { for (int j = 0; j < testSize; j++) { int index = test.toIndex(i, j); int coordinates[] =...

What's wrong with my nested for loop in R?

r,for-loop,matrix,average,moving-average

this should get you started (even though I would convert the matrices to data.frames): #some sample data m <- matrix(sample(10000, 365*4),365,4) # get the mean of all the columns of your matrix colMeans(m) if you have 3 matrices and you want to combine the results I would do: # some...

Summing multiple columns to equal -1,0,1 [closed]

r,matrix,data.frame

The product can be calculated thusly: df <- data.frame(x=c(1,1,1,1,0,-1), y=c(1,0,1,1,0,1), z=c(0,0,1,1,1,1), Total=c(2,1,3,3,1,2), row.names=c('2013-07-01','2013-07-02','2013-07-03','2013-07-05','2013-07-08','2013-07-09') ); df$Total <- df$x*df$y*df$z; df; ## x y z Total ## 2013-07-01 1 1 0 0 ## 2013-07-02 1 0 0 0 ## 2013-07-03 1 1 1 1 ## 2013-07-05 1 1 1 1 ## 2013-07-08 0...

Pairwise correlations over rolling periods ignoring double calculations

matrix,stata,correlation

@William Lisowski debugged your code in a comment, but you can simplify the whole procedure. Create the tuples beforehand using the user-written command tuples (ssc install tuples). clear set more off *----- example data ----- sysuse auto keep mpg weight price gen time = _n tsset time *----- what you...

MATLAB removing rows which has duplicates in sequence

arrays,matlab,matrix

So you want to remove rows of A that contain at least t zeros in sequence. How about a single line? B = A(~any(conv2(1,ones(1,t),2*A-1,'valid')==-t, 2),:); How this works: Transform A to bipolar form (2*A-1) Convolve each row with a sequence of t ones (conv2(...)) Keep only rows for which the...

Matrix / vector multiplication order

opengl,math,matrix,vector

Your C++ matrices are probably stored as row major under the hood. Which means that multiplying them from left to right is an "origin" transformation, while right to left would be a "local" incremental transformation. OpenGL however uses a column major ordering memory layout (The 13th, 14th and 15th elements...

How to solve for matrix in Matlab?

matlab,matrix,least-squares

Rewrite the quantity to minimise as ||Xa - b||^2 = (definition of the Frobenius norm) Tr{(Xa - b) (Xa - b)'} = (expand matrix-product expression) Tr{Xaa'X' - ba'X' - Xab' + bb'} = (linearity of the trace operator) Tr{Xaa'X'} - Tr{ba'X'} - Tr{Xab'} + Tr{bb'} = (trace of transpose of...

Clustering a large, very sparse, binary matrix in R

r,performance,matrix,cluster-analysis,sparse-matrix

I've written some Rcpp code and R code which works out the binary/Jaccard distance of a binary matrix approx. 80x faster than dist(x, method = "binary"). It converts the input matrix into a raw matrix which is the transpose of the input (so that the bit patterns are in the...

matlab Create growing matrix with for loop that grows by 3 per loop

matlab,loops,for-loop,matrix

Here is your problem: HSRXp(:,i*3) = [HSRXdistpR(:,i) HSRXdistpL(:,i) TocomXdistp(:,i)]; You're trying to assign an n x 3 matrix (RHS) into an n x 1 vector (LHS). It would be easier to simply use horizontal concatenation: HSRXp = [HSRXp, [HSRXdistpR(:,i) HSRXdistpL(:,i) TocomXdistp(:,i)]]; But that would mean reallocation at each step, which...

Is there a more efficient way to solve this?

python,python-2.7,optimization,matrix

In terms of refactoring, you almost certainly want to avoid "brute force" in the sense of having to explicitly type out all your cases :) @alexmcf addresses this above. In conceptual terms, your approach follows the problem statement directly: check all neighbors for each number in the matrix and sum...

Fastest way to copy some rows from one matrix to another in OpenCV

c++,matlab,opencv,matrix

So I tried different methods for this problem and the only way I could achieve a better performance than Matlab was using memcpy and directly copying the data myself. Mat out( index.cols, w2c.cols, w2c.type() ); for ( int i=0;i<index.cols;++i ){ int ind = index.at<int>(i)-1; const float *src = w2c.ptr<float> (ind);...

Numpy matrix row comparison

python,performance,numpy,matrix,comparison

Few approaches with broadcasting could be suggested here. Approach #1 out = np.mean(np.sum(pattern[:,None,:] == matrix[None,:,:],2),1) Approach #2 mrows = matrix.shape[0] prows = pattern.shape[0] out = (pattern[:,None,:] == matrix[None,:,:]).reshape(prows,-1).sum(1)/mrows Approach #3 mrows = matrix.shape[0] prows = pattern.shape[0] out = np.einsum('ijk->i',(pattern[:,None,:] == matrix[None,:,:]).astype(int))/mrows # OR out = np.einsum('ijk->i',(pattern[:,None,:] == matrix[None,:,:])+0)/mrows Approach #4...

Finding Numerical Derivative using a shift matrix in MATLAB

matlab,matrix,numerical-methods

This code for the most part does what it intends to do: compute the numerical approximation to the derivative. However, the way you're computing the derivative is slightly incorrect. Basically, for each point in your array, you want to subtract the point to the left with the point to the...

Matlab - Multiply specific entries by a scalar in multidimensional matrix

matlab,matrix,multidimensional-array,scalar

Errr, why you multiply indexes instead of values? I tried this: comDatabe(:,:,[1 2 3],:,8) = comDatabe(:,:,[1 2 3],:,8)*-1 And it worked....

List of coordinates to matrix of distances

python,numpy,matrix,distance

As explained in the scipy documentation, use scipy.spatial.distance.squareform to convert the condensed distance matrix returned by pdist to a square distance matrix, from scipy.spatial.distance import squareform dist_matrix = squareform(dist_array) ...

Join matrices with same values in different vectors in MATLAB

matlab,matrix,merge

You don't need to use a loop, use intersect instead. [~,ic,ip] = intersect(c(:, 1:3),p(:, 1:3),'rows'); m = [c(ic, :), p(ip,end)]; Edit: If you want to include NaNs where they don't intersect like the above poster. function m = merge(c, p, nc, np) %check for input arg errors if nargin ==...

Variable value changing after returning from a function in C

c,variables,matrix

Update the function void allocate( int ***mat, int n, int m ) { int i; *mat = (int **) malloc( n * sizeof( int* ) ); for ( i = 0; i < n; i++ ) { ( *mat )[i] = ( int *) malloc ( m * sizeof( int...

What does three.js's Matrix4.multiply() method do?

javascript,matrix,three.js,linear-algebra,matrix-multiplication

The problem is in how you're iterating the matrix elements to print them. The .elements property returns the elements in column-major order (despite the constructor and .set() methods parameters being in row-major order!). So you should: function logMatrix(matrix) { var e = matrix.elements; var $output = $('#output'); $output.html(e[0] + '...

numpy.matrix and .shape - which number is rows, and which is column?

python,numpy,matrix

rows, columns are just the names we give, by convention, to the 2 dimensions of a matrix (or more generally a 2d numpy array). np.matrix is, by definition, 2d, so this convention is useful. But np.array may have 0, 1, 2 or more dimensions. For that these 2 names are...

Error return from the MODISSummaries function (R package MODISTools)

r,matrix,error-handling

Thanks for highlighting this bug. I've pushed a fix to my GitHub repository (https://github.com/seantuck12/MODISTools/). I will update the version on CRAN as soon as possible but in the meantime please use the GitHub version.

writing matrix columns with different precisions(significant digits) in matlab

matlab,matrix,precision,significant-digits

maybe something simple like this? m = [10 15.675; 13.5 34.987; 20 55.5]; file = fopen('file.txt', 'w'); for ii = 1:size(m, 1) fprintf(file, '%0.1f %0.2f\n', m(ii, 1), m(ii, 2)); end I've edited to add the '\n'...

multiply each columns of a matrix by a vector [closed]

r,matrix

vect*mat [,1] [,2] [,3] [,4] [1,] 2 8 14 20 [2,] 4 10 16 22 [3,] 6 12 18 24 The vector vect is recycled by column. Better to experiment with different values to see the process....

How to subset by distinct rows in a data frame or matrix?

r,matrix,filter,data.frame,subset

Try this: (I suspect will be faster than any apply approach) mat[ rowSums(mat == mat[,1])!=ncol(mat) , ] # ---with your object--- [,1] [,2] [,3] [1,] 1 2 3 [2,] 1 3 2 ...

How to select different row in a matrix in Matlab every time?

matlab,matrix

You could use randperm to mess up the rows randomly and then take two rows in each iteration successively in order. iterations = 4; permu = randperm(size(A,1)); out = A(permu(1:iterations*2),:); for ii = 1:iterations B = out(2*ii - 1:2*ii,:) end Results: B = 22 23 24 25 26 27 B...

a vector to an upper Triangle matrix by row in R

r,matrix,vector

Here's one option b[lower.tri(b, diag=FALSE)] <- a b <- t(b) b # [,1] [,2] [,3] [,4] # [1,] 0 1 2 3 # [2,] 0 0 4 5 # [3,] 0 0 0 6 # [4,] 0 0 0 0 Alternatively, reorder a as required and assign that into the...

Matrix indexing using vectors in Matlab [duplicate]

matlab,matrix

As you have experienced, MATLABs indexing doesn't work that way. To get a feeling for the ways indexing works in MATLAB, please have a look at this nice article from Mathworks. Now how to tackle your problem: The solution is to use linear indexing. You can always index a 2-dimensional...

R - loop and break after value found for each Rows

r,loops,matrix,break

You seem to be fond of for loops and those seem like a natural choice here. Just change your code to this: for(i in 1:nrow(matSolo)){ for(j in 1:ncol(matSolo)){ if(SoloNight[i,j] == 1) { matSolo [i,j] <- 1 break } } } However, this will be quite slow for big matrices. Fortunately,...

Fortran Seg Fault when assigning Matrices

matrix,segmentation-fault,fortran,derived-types

After narrowing down the issue to using numbers vs. variables of those same numbers, it was discovered that Fortran doesn't like assigning a matrix to a matrix of different dimensions even if it fit inside. This was weird because smaller values of M, N, and Nblock got around the issue...

What is an efficient way of multiplying massive polynomials in Java?

java,matrix,polynomials

Maybe this idea will help you to solve your problem: int result = 1; int x = 2; int y = 3; Integer [][] polynomials = new Integer[x][y]; polynomials[0][0] = 1; polynomials[0][1] = 2; polynomials[0][2] = 3; polynomials[1][0] = 4; polynomials[1][1] = 5; polynomials[1][2] = 6; for(int i = 0;...

Why does this code double transpose a vector - is this a noop?

r,matrix,transpose

Have a look at the structure using str: > str(a); str(b); str(c) int [1:20] 1 2 3 4 5 6 7 8 9 10 ... int [1, 1:20] 1 2 3 4 5 6 7 8 9 10 ... int [1:20, 1] 1 2 3 4 5 6 7 8...

How do I scale the graphics of a game?

c#,matrix,xna,window,scale

By default, SpriteBatch assumes that your world space is the same as client space, which is the size of the window. You can read about SpriteBatch and different spaces in a post by Andrew Russell. When you are resizing the backbuffer, the window size will also change changing the world...

Fast access to matrix as jagged array in C#

c#,performance,matrix,jagged-arrays

You could remove the conditional in the method and increase memory usage to increase access performance like so: var dm = new double[size][]; for (var i = 0; i < size; i++) { dm[i] = new double[size]; for (var j = 0; j < i+1; j++) { dm[i][j] = distance(data[i],...

Windows Form: change dataGridView's first cell origin?

c#,winforms,matrix,datagridview

Create one class like this: public class MyDataGridView : DataGridView { public new DataGridViewCell this[int col, int invertRow] { get { int recordCount = this.RowCount - (this.AllowUserToAddRows ? 2 : 1); return this.Rows[recordCount - invertRow].Cells[col]; } set { int recordCount = this.RowCount - (this.AllowUserToAddRows ? 2 : 1); this.Rows[recordCount -...

Polynomial multiplication in M2(R)?

algorithm,matrix,fft,polynomials

You can not expect this method to work if your coefficient matrices do not commute with your matrix step. To get it working correctly, use the diagonal matrix corresponding to multiplication with the scalar exp(i*2*PI/M).

find indices x,y of a matrix of specific values in python

python,matrix,multidimensional-array,indices

You need to change your where line to something like: data_indices = numpy.where((data<=obj_value_max) & (data>=obj_value_min)) Notice the ()s around each conditional clause and the use of & (meaning "and"). This works because in numpy, <,<=,>,>=,&,|,... are overridden, i.e. they act differently than in native python. and and or cannot be...

Modify a matrix in ocaml

matrix,ocaml

In an expression the = operator in OCaml is a comparison operator that tests for equality. To assign to an array, use the <- operator. The compiler is complaining because your expression has type bool (i.e., the result of the comparison). The expression in a for should have type unit...

Create a Triangular Matrix from a Vector performing sequential operations

r,for-loop,matrix,vector,conditional

Using sapply and ifelse : sapply(head(vv[vv>0],-1),function(y)ifelse(vv-y>0,vv-y,NA)) You loop over the positive values (you should also remove the last element), then you extract each value from the original vector. I used ifelse to replace negative values. # [,1] [,2] [,3] [,4] [,5] # [1,] NA NA NA NA NA # [2,]...

Randomly select Elements of 4D matrix in Matlab

matlab,matrix,random,4d

If I am interpreting what you want correctly, for each unique 3D position in this matrix of 7 x 4 x 24, you want to be sure that we randomly sample from one out of the 10 stacks that share the same 3D spatial position. What I would recommend you...

Count of an element in a matrix using Divide & Conquer

c++,algorithm,matrix,divide-and-conquer

Here is the corrected source code. I have added some comments so you can follow it. Furthermore, I switched to a dynamic array of the correct size. #include<fstream> #include<conio.h> #include<iostream> using namespace std; int countOccurences(int** values, int min1, int min2, int max1, int max2, int searchValue) { if (min1 >...

In place modification of matrices in R

r,matrix,data.table,copy-on-write

I get the same behaviour as the OP using R 3.2.0 running within RStudio 0.99.441 on Windows 8.1 and using pryr::address. The issue is RStudio has a reference to y for its Environment pane. As often the case, Hadley Wickham has some excellent documentation of this. I don't think there's...

Add a matrix of 2x2 into a vector in c++

c++,matrix,vector

You cannot push back a matrix into a vector. What you can do is preallocate memory for your vector (for speeding things up) then use the std::vector<>::assign member function to "copy" from the matrix into the vector: vector<int> collectionSum(gray.rows * gray.cols); // reserve memory, faster collectionSum.assign(*auxMat, *auxMat + gray.rows *...

Delete a column and a row in a square matrix in C

c,matrix

Well, to do this, you'll have to realise that in memory your matrix is actually a list of lists. This means that removing a column is slightly different from removing a row: Assuming your syntax is matrix[row][column]; void removeColumn(int** matrix, int col){ MATRIX_WIDTH--; //TODO check for empty matrix etc; for(int...

solvePnP: Obtaining the rotation translation matrix

c++,opencv,matrix,computer-vision,transform

Reading the (excellent) OpenCV documentation for solvePnP might help: "rvec – Output rotation vector (see Rodrigues() ) that, together with tvec , brings points from the model coordinate system to the camera coordinate system." And following the link to Rodrigues(): src – Input rotation vector (3x1 or 1x3) or rotation...

How do I apply multiple matrices in spriteBatch.Draw()?

c#,matrix,xna

Simply multiply the matrices before passing to spriteBatch.Begin. Matrix multiplication allows the effects of both matrices appended into a single matrix. Note that this operation is not commutative, meaning that A * B != B * A. In your case, you should probably multiply scaling matrix with the camera matrix....

Factorial of a matrix elementwise with Numpy

python,numpy,matrix,factorial

There's a factorial function in scipy.misc which allows element-wise computations on arrays: >>> from scipy.misc import factorial >>> factorial(mat) array([[ 1., 2., 6.], [ 2., 6., 24.]]) The function returns an array of float values and so can compute "larger" factorials up to the accuracy floating point numbers allow: >>>...

Handling large matrices in C++

c++,c++11,matrix

If a variable number of dimensions above 2 is a key requirement, take a look at boost's multidimensional array library. It has efficient (copying free) "views" you can use to reference lower-dimensional "slices" of the full matrix. The details of what's "fastest" for this sort of thing depends an awful...

Treating 2d array data as pixels defining a shape - is it possible to create an inside and a surface?

python,arrays,matrix,pixel,surface

You can just check the value and the direct neighborhood of every pixel: Your resulting image is 1 where: the original value was 1 and at least one neighbor is 0 It is 0 everywhere else. The image below might help to illustrate what I mean: The center pixel of...

Interpolation inside a matrix. Matlab

matlab,matrix

M =[0 0 0 0 0 1 0 0 0 0 0 2 0 0 0 0 0 2 0 0 0 0 0 1 0 1 0 0 0 1 0 4 0 0 0 0 0 3 0 0 6 0 0 4 0 0 3 0 0...

Initialize matrix

python-2.7,matrix

becouse the first line is filling a matrix the second matrix definition is actually creating an array of size 1 with another array as the 0 element the moment i=1 it fails the correct form of the second part should be matrix = [] for i in range(6): temp =...

Sum of n-1 columns of a double matrix in MATLAB

matlab,matrix

You can do that by using the function cumsum: A = [1 2 3 4 5 6]; C = cumsum(A); out = [0 C(1:end-1)] now out is: [0 1 3 6 10 15]...

How to join two matrices in fprintf in MATLAB?

matlab,matrix

@Anatch is right, you can use horzcat(A,B) to horizontally concatenate two matrices. Though a simpler way to do the same thing is simply saying [A B], to concatenate horizontally or [C; A] to concatenate vertically. As for printing these results, @SamuelNLP 's solution works, but here's an alternative, which is...

Functions with double pointer arrays - find the max in a matrix

c,arrays,matrix

You allocated memory for a but not for the rows of a. for( c = 0 ; c < m ; c++ ) { // Add this a[c] = malloc(n*sizeof(int)); for( d = 0 ; d < n ; d++ ) { scanf("%d",&a[c][d]); } } Also, make sure to add...

Creating a matrix based on a function in R

r,matrix,data.frame

Is that what you want? 1-cov2cor(A) [,1] [,2] [,3] [,4] [,5] [1,] 0.0000000 0.5232687 0.6348516 0.7000000 0.8174258 [2,] 0.5232687 0.0000000 0.5648059 0.6186150 0.7388835 [3,] 0.6348516 0.5648059 0.0000000 0.5435645 0.5000000 [4,] 0.7000000 0.6186150 0.5435645 0.0000000 0.8174258 [5,] 0.8174258 0.7388835 0.5000000 0.8174258 0.0000000 ...

R - Check different matrices with a possible lag

r,loops,matrix,lag

Here's a simple way to do it: lag <- 3 # or whatever lag you want nr <- nrow(mat1) nc <- ncol(mat1) mat3 <- matrix(0, ncol=nc, nrow=nr) for (r in 1:nr) { for (c in 1:nc) { if (mat1[r,c] == 1 && any(mat2[r,c:min(c+lag,nc)] == 1)) mat3[r,c] <- 1 } }...

Computing time complexity of the sparse matrix (2)

r,matlab,matrix,sparse-matrix

For every (i, j) pair (there are n^2 in total), you reach the inner part of the loop where you find the similarity and then conditionally add elements to your sparse matrix. Finding the similarity takes "d" operations (because you need to loop through each of your dimensions) and conditionally...

Add coefficients of a vector to a matrix

r,matrix,vector

try this: M + rep(x, each = nrow(M)) or this: apply(M, 1, `+`, x) result: [,1] [,2] [,3] [1,] 6 7 8 [2,] 7 8 9 [3,] 8 9 10 EDIT: akrun commented on two other great solutions: M + x[col(M)] and sweep(M, 2, x, "+") ...

Numpy and dot products of multiple vector pairs: how can it be done?

python,numpy,matrix,scipy

np.einsum would do it: np.einsum('ij,ij->i', a_vec, b_vec) ...

Determining regression coefficients for data - MATLAB

matlab,matrix,regression,numerical-methods

This sounds like a regression problem. Assuming that the unexplained errors in measurements are Gaussian distributed, you can find the parameters via least squares. Basically, you'd have to rewrite the equation so that you get this to the form of ma + nb + oc = p and then you...

How to convert a vector into a matrix by names in R?

r,matrix

Neither pretty or fast but you can do something like this using data.table::rbindlist library(data.table) # Create list of lists splitting data by ID and convert to data.table dt <- rbindlist(tapply(x, cumsum(names(x) == "ID"), as.list), fill=TRUE) # Ensure column order setcolorder(dt, c('ID', 'var1', 'var2', 'var3')) # Convert to matrix as.matrix(dt) ...

I can't fix camera to any object in a 2D Matrix

c#,matrix,camera,xna,viewport

The reason you are getting NullReferenceException is because GraphicsDevice is not initialized yet. Instead of creating your Camera in the TheGame constructor, create it in the Initialize method: protected override void Initialize() { base.Initialize(); camera = new Camera(GraphicsDevice); } How to make camera fixed on any object in the Matrix...

Multipling row and column vector using .* operation

matrix,octave,matrix-multiplication,broadcasting

This is because Octave (in a notable difference from Matlab) automatically broadcasts. The * operator in Octave is the matrix multiplication operator. So in your case a*b would output (in Matlab as well) a*b ans = 1 2 3 2 4 6 3 6 9 which should be expected. The...

Linear equation solver Arduino,printing wrong answers

c,matrix,arduino,calculator,linear-algebra

It's a floating point error, the final value you are getting is very close to zero. Demo. Add a small epsilon value to your final test to allow for floating point inaccuracies: if(fabs(a[cant-1][cant-1]) < 0.000001){ lcd.print("No solucion"); /* if there is no solution print this*/ ...

Extract raw model matrix of random effects from lmer objects (lme4, R)

r,matrix,sparse-matrix,lme4,lmer

If mmList is there, then it's not going away (however poorly documented it may be -- feel free to suggest documentation improvements ...). How about do.call(cbind,getME(m2,"mmList")) (which would seem to generalize correctly for multi-term models)? I agree that it's a bit of a pain that Zt doesn't distinguish correctly between...

importing specific information of a text file into a matrix

matlab,text,matrix

Here you go, there were some indexing errors %% fid=fopen('fic.txt'); l=fgetl(fid); k=1; while ischar(l) r{k}=l; k=k+1; l=fgetl(fid); end fclose(fid); idx=find(~cellfun(@isempty,regexp(r,'(?=timestep).+'))); a=regexp(r(idx),'\d+','match'); b=str2double([a{:}]); ii=diff([idx numel(r)+1])-1; for k=1:numel(b); s=r(idx(k)+1:idx(k)+ii(k)); jj=find(~cellfun(@isempty,regexp(s,'(?=H2O ).+'))); c=regexp(s(jj),'\d+','match'); if isempty(c) f(k)=0; else f(k)=str2double(c{1}(2)); end end M=[b' f'] ...

Iteratively and randomly adding ones to a binary vector in matlab

matlab,matrix

If it's important to have the intermediate vectors (those with 1, 2, ... 4 ones) as well as the final one, you can generate a random permutation and, in your example, use the first 5 indices one at a time: n = 9; %// number of elements in vector m...

Indexing an array in MATLAB

matlab,matrix

You can index arrays in this way: value = x(1)/A(1) By the way A(1) is not 3, but 0.003...

Multiply high order matrices with numpy

python,numpy,matrix,scipy

You could use np.einsum to do the operation since it allows for very careful control over which axes are multiplied and which are summed: >>> np.einsum('ijk,ij->ik', ind, dist) array([[ 0.4, 0.4, 0.4, 0.4], [ 3. , 3. , 3. , 3. ], [ 1. , 1. , 1. , 1....

Storing columns on disk and reading rows

c++,file,matrix,io

Mentioned solution with fseek is good. However, it can be very slow for large matrices (as disks don't like random access, especially very far away). To speed up things, you should use blocking. I'll show a basic concept, and can explain it further if you need. First, you split your...

A function to calculate cumulative maximum for a double matrix in MATLAB

matlab,function,matrix,max

If cummax isn't working then I came up with this little function function m = cummax2(x) [X, ~] = meshgrid(x, ones(size(x))); %replace elements above diagonal with -inf X(logical(triu(ones(size(X)),1))) = -inf; %get cumulative maximum m = reshape(max(X'), size(x)); end ...

Spiral traversal of a matrix - recursive solution in JavaScript

javascript,arrays,algorithm,recursion,matrix

Your code is very close but it is doing more than it needs to do. Here I simplify and bug fix: var input = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]; var spiralTraversal = function(matriks){ var result = []; var goAround...

Matrix Transformation in R - from aggregate output to outer-like matrix

r,matrix,aggregate,transformation,outer-join

You can try tapply with(mtcars, tapply(disp, list(cyl, gear), FUN=mean)) # 3 4 5 #4 120.1000 102.625 107.7 #6 241.5000 163.800 145.0 #8 357.6167 NA 326.0 If you are looking to reshape the output of aggregate, we can use acast from reshape2 d1 <- aggregate(disp ~ cyl + gear, data =...

sorting of month in matrix in R

r,sorting,matrix

Suppose DF is the data frame from which you derived your matrix. We provide such a data frame in reproducible form at the end. Ensure that month and year are factors with appropriate levels. Note that month.name is a builtin variable in R that is used here to ensure that...