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 *...

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); ...

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...

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])...

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.

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[] =...

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...

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 } }...

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...

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...

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...

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 =...

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....

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...

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'] ...

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...

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) ...

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] + '...

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...

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*/ ...

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...

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...

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() ...

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...

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 }...

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,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'...

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,]...

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;...

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,...

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...

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...

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...

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],...

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...

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...

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...

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] << " "; }...

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...

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,:); ...

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: >>>...

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...

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 ...

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...

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...

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...

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 -...

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....

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,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 =...

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,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...

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...

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

@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...

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...

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 ...

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...

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 ==...

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, "+") ...

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...

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...

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...

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...

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...

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...

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

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...

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 ...

>>> 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. >>>...

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]...

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...

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...

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...

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...

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...

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);...

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]...

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....

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...

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...

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....

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 >...

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...

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...

@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...

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).

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 ...

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....

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...