Menu
  • HOME
  • TAGS

Fastest solution to list all pairs of n integers?

Tag: performance,matlab,matrix,combinations,combinatorics

I want to list all possible pairs of the integers [1, n] with a large n. I find myself looking for the fastest option. This is what I've come up with so far.

Matlab's nchoosek and combnk methods recommend n<15 for listing all possible combinations because of the explosive number of combinations. So how fast this is depends on the n.

pair = nchoosek(1:n, 2);

Another option would be to use a nested for loop

kk =1;
pair = zeros(nchoosek(n, 2), 2);
for ii = 1:n
    for jj = ii+1:n
        pair(kk, :) = [ii, jj];
        kk = kk + 1;
    end
end  

This would be relatively slow.

I also thought of using the ind2sub function directly

pair_adjacency = tril(ones(n),  -1);
[x, y] = ind2sub(size(pair_adjacency), find(pair_adjacency==1)); 
pair = [x, y];

Timing these methods in a loop, 10 times each with n=1000, I get fastest to slowest

  1. ind2sub (0.15 sec)
  2. for loop (16.3 sec)
  3. nchoosek (16.8 sec)

It seems like ind2sub is the fastest way to go by a long shot. Just out of curiosity, what are other options that may or may not be faster?

Best How To :

To replace nchoosek(1:N,2)

With bsxfun -

[Y,X] = find(bsxfun(@gt,[1:N]',[1:N]))
pair = [X, Y];

With tril and find only (without ind2sub) -

[y,x] = find(tril(true(N),-1))
pair = [X, Y];

Dynamic creation of objects vs storing them as fields

java,performance,object

There won't be any difference, since you've only changed the scope of the variables. Since you're not using the variables outside of the scope, the generated bytecode will be identical as well (you can try it out with javap). So use the second style for clarity. Edit: In fact if...

Matlab Distribution Sampling

matlab,distribution,sampling,random-sample

So, you can use this, for example: y = 0.8 + rand*0.4; this will generate random number between 0.8 and 1.2. because rand creates uniform distribution I believe that rand*0.4 creates the same ;) ...

How to force my output data in a inputdlg on Matlab be a double?

matlab,typeconverter

inputdlg returns a cell array of strings. You can convert to double with str2double: units = str2double(inputdlg(question, title)); ...

MySQL - How can I know my query is tuned?

mysql,performance,explain

Except for trivial queries, there is no way to know if you have the optimal query & indexes. Nor can you get a metric for how well designed the schema and application are. 3 seconds on a cold system for a 3-way JOIN with "Rows" of 409, 45, 1 is...

MATLAB Access Classreg

matlab

You can read the file using: >> open classreg.regr.modelutils.tstats This will open "tstats.m". The path of that file on your drive can be a acccessed using: >> which classreg.regr.modelutils.tstats In this folder there are all the other m-files which belong to this class....

Creating a cell array of workspace variables without manually writing them all out. MATLAB

matlab

Not the fastest way, but you could do it as follows: Saving the desired variables in a temporary file Loading that file to get all those variables in a struct array Converting that struct array to a cell array That is, save temp_file -regexp data\d+ %// step 1 allData =...

Angular ng-repeat cache (avoid re-rendering on state change)

javascript,angularjs,performance,caching,angularjs-ng-repeat

Well if you disable the scope of the scope that the ng-repeat is on. Then it will no longer render. It essentially becomes static content. This allows you to actually control when it is rendered. ux-datagrid actually uses this concept to turn off dom that is out of view so...

Giving a string variable as a filename in matlab

string,matlab,filenames

You would need to change your back slashes \ to forward slashes /, otherwise some \ followed by a letter may be commands in the sprintffunction, like for example \N or \a. See sprintf documentation in the formatSpecarea for more information. original_image=imread(sprintf('D:/Academics/New folder/CUB_200_2011/images/%s', C{1}{2*(image_count)})); ...

performance issues executing list of stored procedures

c#,multithreading,performance,loops

What I would do is something like this: int openThread = 0; ConcurrentQueue<Type> queue = new ConcurrentQueue<Type>(); foreach (var sp in lstSps) { Thread worker = new Thread(() => { Interlocked.Increment(ref openThread); if(sp.TimeToRun() && sp.HasResult) { queue.add(sp); } Interlocked.Decrement(ref openThread); }) {Priority = ThreadPriority.AboveNormal, IsBackground = false}; worker.Start(); } //...

How to access variables in the properties block of a Matlab System Object?

matlab,simulink

You should be able to use properties s = 100; d = zeros(1,100); end right? If you already have the 100 as a default for s, you should also be able to provide this as part of the default for d. I'm guessing that you're trying to avoid doing that...

how to calculate probability for each class for predicate with knn without fitcknn?

matlab

First, you have to know that fitcknn & ClassificationKNN.fit will end up with the same result. The difference is that fitcknn is a more recent version, so it allows more options. As an example, if you use load fisheriris; X = meas; Y = species; Then this code will work...

Connecting two binary objects in matlab

matlab,image-processing

Morphological operations are suitable but i would suggest line structuring element as your arrangement is horizontal and you do not want overlaps between lines: clear clc close all BW = im2bw(imread('Silhouette.png')); BW = imclearborder(BW); se = strel('line',10,0); dilateddBW = imdilate(BW,se); img= imerode(BW,se); figure; imshow(img) ...

How to normalise polynomial coefficients in a fraction?

matlab,polynomial-math

You can extract the numerator and denominator with numden, then get their coefficiens with coeffs, normalize the polynomials, and divide again. [n,d] = numden(T); cn = coeffs(n); cd = coeffs(d); T = (n/cn(end))/(d/cd(end)); The output of latex(T) (note: no simplifyFraction now; it would undo things): Of course this isn't equal...

Synchronize local SQLite database with central database

android,performance,sqlite,compare

In your case needs value the situation!! When I have this problems the first questions are... The tables that I want to do 'drop table' have few data? If it's yes the best way is the 'drop table' command. If it's no then you need to use the 'insert' and...

matlab plots as movie with legend

matlab,plot,legend,movie

The strings defined in the legend command are assigned in order of the plots being generated. This means that your first string 'signal1' is assigned to the plot for signal1 and the second string 'signal2' is assigned to the vertical line. You have two possibilities to fix this problem. Execute...

Matlab: Looping through an array

matlab,loops,for-loop,while-loop,do-while

You could do this using conv without loops avg_2 = mean([A(1:end-1);A(2:end)]) avg_4 = conv(A,ones(1,4)/4,'valid') avg_8 = conv(A,ones(1,8)/8,'valid') Output for the sample Input: avg_2 = 0.8445 5.9715 -0.6205 -3.5505 2.5530 6.9475 10.6100 12.5635 6.4600 avg_4 = 0.1120 1.2105 0.9662 1.6985 6.5815 9.7555 8.5350 avg_8 = 3.3467 5.4830 4.7506 Finding Standard Deviation...

Plot multiple functions on one figure

matlab,matlab-figure

I think you are missing the x limit. xlim([0 2.5*a]) ...

Operating a C++ class from Matlab without mex [closed]

c++,matlab

You can use calllib to call functions in shared library. This would be the newlib.h #ifdef __cplusplus extern "C"{ #endif void *init(int device); #ifdef __cplusplus } #endif and this would be the newlib.cpp file #include "newlib.h" #include "yourlib.h" A *p; extern "C" void *init(int device) { p = new A;...

Can we add a statement in between MATLAB codes?

matlab

You need to comment those statements like this r(:,1) = a(:,1) ... % this is a constant - a(:,2); % this is a variable for more information read this ...

Create mask from bwtraceboundary in Matlab

image,matlab,image-processing,mask,boundary

It's very simple. I actually wouldn't use the code above and use the image processing toolbox instead. There's a built-in function to remove any white pixels that touch the border of the image. Use the imclearborder function. The function will return a new binary image where any pixels that were...

How to count the number of zero decimals in javascript?

javascript,performance

You can use logarithms to find the magnitude of the number: var x = 0.00195; var m = -Math.floor( Math.log(x) / Math.log(10) + 1); document.write(m); // outputs 2 (Later versions of JavaScript have Math.log10.)...

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

Do you get the same performance using index prefixes?

performance,mongodb,indexing

A "compound index" which is the correct term for your "link" does not create any performance problems on "read" ( since writing new entries is obviously more information ) than an index just on the single field used in the query. With one exception. If you use a "multi-Key" index...

xcorr function with impulse response

matlab,filtering,convolution

The following code implements only a part of what I can see in the description. It generates the noise processes and does what is described in the first part. The autocorrelation is not calculated with the filter coefficients but with the actual signal. % generate noise process y y =...

Insert multiple rows into MySQL table

java,mysql,sql,performance

Is this what you want? insert into mytable(name, uuid, . . .) select name, uuid, . . . from mytable where x between $xmin and $xmax and y between $ymin and $ymax; If it is something like this, then you only need one query, just the right conditions....

Create string without repeating the same element jn the string (Matlab)

string,matlab

Use unique with the 'stable'option: str = 'FDFACCFFFBDCGGHBBCFGE'; result = unique(str, 'stable'); If you want something more manual: use bsxfun to build a logical index of the elements that haven't appeared (~any(...)) before (triu(..., 1)): result = str(~any(triu(bsxfun(@eq, str, str.'), 1))); ...

Why can't I calculate CostFunction J

matlab,machine-learning

As suggested in the comments, the error is because x is of dimension 3x2 and theta of dimension 1x2, so you can't do X*theta. I suspect you want: theta = [0;1]; % note the ; instead of , % theta is now of dimension 2x1 % X*theta is now a...

Plotting random signal on circle

matlab,plot,signals,circle

You need to add "noise" to the radius of the circle, roughly around r=1: th = linspace( 0, 2*pi, N ); %// N samples noise = rand( 1, N ) * .1; %// random noise in range [0..0.1] r = 1+noise; %// add noise to r=1 figure; plot( r.*cos(th), r.*sin(th)...

Why black surf from this Matlab command?

matlab,time-frequency

My bet is that trf is a very large matrix. In these cases, the surface has so many edges (coloured black by default) that they completely clutter the image, and you don't see the surface patches One solution for that is to remove the edges: surf(trf, 'edgecolor', 'none'). Example: with...

Should I pass all the state in every change from store to component?

javascript,performance,reactjs,reactjs-flux,flux

Yes, that is okay for a real app. It is typical to emit whole objects from stores even if it just so happens one of the listeners only needs a subset of the data. The idea is to keep it simple and avoid having to change the store when what...

Animate through multiple 2D Matlab plots

matlab,plot

I assume with "2d-line" you mean a 2d-plot. This is done by the plot-function, so there is no need of surf or mesh. Sorry, when I got you wrong. The following code does what I think you asked for: % Generate some propagating wave n = 20; t = linspace(0,10,100);...

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

How to prevent exceeding matrix dimensions while dividing an image into blocks?

image,matlab,image-processing,image-segmentation

If you simply want to ignore the columns/rows that lie outside full sub-blocks, you just subtract the width/height of the sub-block from the corresponding loop ranges: overlap = 4 blockWidth = 8; blockHeight = 8; count = 1; for i = 1:overlap:size(img,1) - blockHeight + 1 for j = 1:overlap:size(img,2)...

Matlab — SVM — All Majority Class Predictions with Same Score and AUC = .50

matlab,svm,auc

Unless you have some implementation bug (test your code with synthetic, well separated data), the problem might lay in the class imbalance. This can be solved by adjusting the missclassification cost (See this discussion in CV). I'd use the cost parameter of fitcsvm to increase the missclassification cost of 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....

SQL Server Query Performance with Timestamp and variable

sql-server,performance,timestamp

My guess is that you also have an index on MachineName - or that SQL is deciding that since it needs to group by MachineName, that would be a better way to access the records. Updating statistics as suggested by AngularRat is a good start - but SQL often maintains...

Fastest way to draw sprites in opengles 2.0 on android

android,performance,opengl-es,opengl-es-2.0

I think you're after a particle system. A similar question is here: Drawing many textured particles quickly in OpenGL ES 1.1. Using point sprites is quite cheap, but you have to do extra work in the fragment shader and I'm not sure if GLES2 supports gl_PointSize if you need different...

solve symbolic system of equations inside an array

matlab,system,equation

Generally this is done (if the eq is in the format you have) with an Ax=b system. Let me show you how to do it with a simple example of 2 eq with 2 unknowns. 3*l1-4*l2=3 5*l1 -3*l2=-4 You can build the system as: x (unknowns) will be a unknowns...

performance of executing openjpa query

java,performance,jpa,openjpa

The problem is that you are measuring two different things.164 ms is the time that the database spent executing the query. I suspect the 824 ms that you measured is query execution + instantiation of your Entity objects.

Universal function for getting all unique pairs, trebles etc from an array in javascript

javascript,jquery,arrays,performance,underscore.js

Basically combine() takes an array with the values to combine and a size of the wanted combination results sets. The inner function c() takes an array of previously made combinations and a start value as index of the original array for combination. The return is an array with all made...

How to switch Matlab plot tick labels to scientific form?

matlab,plot

You can change the XTickLabels property using your own format: set(gca,'XTickLabels',sprintfc('1e%i',0:numel(xt)-1)) where sprintfc is an undocumented function creating cell arrays filled with custom strings and xt is the XTick you have fetched from the current axis in order to know how many of them there are. Example with dummy data:...

thicken an object of image to a curve in matlab

matlab,image-processing

This is called "skeletonization" and you can do it with the function bwmorph: bwmorph(Img, 'skel', Inf); Best...

How to print iterations per second?

python,performance,loops,cmd,progress

You can get a total average number of events per second like this: #!/usr/bin/env python3 import time import datetime as dt start_time = dt.datetime.today().timestamp() i = 0 while(True): time.sleep(0.1) time_diff = dt.datetime.today().timestamp() - start_time i += 1 print(i / time_diff) Which in this example would print approximately 10. Please note...

function wait to execute

matlab,events,delay

The "weird behavior and lag" you see is almost always a result of callbacks interrupting each other's execution, and repeated unnecessary executions of the same callbacks piling up. To avoid this, you can typically set the Interruptible property of the control/component to 'off' instead of the default 'on', and set...

what does ellipsis mean in a Matlab function's argument list?

matlab

http://www.mathworks.com/help/matlab/matlab_prog/continue-long-statements-on-multiple-lines.html Continue Long Statements on Multiple Lines This example shows how to continue a statement to the next line using ellipsis (...). s = 1 - 1/2 + 1/3 - 1/4 + 1/5 ... - 1/6 + 1/7 - 1/8 + 1/9; ...

Saving images with more than 8 bits per pixel in matlab

image,matlab,image-processing,computer-vision

You can use the bitdepth parameter to set that. imwrite(img,'myimg.png','bitdepth',16) Of course, not all image formats support all bitdepths, so make sure you are choosing the the right format for your data....

Reading all the files in sequence in MATLAB

matlab,image-processing

From the Matlab forums, the dir command output sorting is not specified, but it seems to be purely alphabetical order (with purely I mean that it does not take into account sorter filenames first). Therefore, you would have to manually sort the names. The following code is taken from this...

MATLAB - How to merge figure sections vertically

matlab,plot

This is quite simple; just feed into subplot the locations as a vector. For instance, x = -2*pi:0.01:2*pi; subplot(2,2,[1,3]) plot(x,sin(x)) subplot(2,2,2) plot(x,cos(x)) subplot(2,2,4) plot(x,x.^2) gives: ...

two dimensional unique values in Matlab

arrays,matlab

See docs for unique. Assuming widths and heights are column vectors, [C,ia,ic] = unique([widths, heights],'rows') In contrary, if widths and heights are row vectors, [C,ia,ic] = unique([widths; heights].','rows') ...

How to make this code more performant?

performance,go,hashmap

You don't need the outer loop as one improvement: func getFields(filter map[string]map[string]bool, msg *Message) (fs []Field) { if fieldFilter, ok := filter[relationString(msg)]; ok { for _, f := range msg.Fields { if _, ok := fieldFilter[f.Name]; ok { fs = append(fs, f) } } } } return } ...