how to accelerate the process of `find` in large for loop ?
i have two arrays a,b. i want to find the index of every element of b in a. i'm sure that every element of b must appears in a twice. the code of mini case is as below.
a = [1 2 3 4 5 6 5 4 2 7];
b = [2 4 5];
result = zeros(length(b),2);
for i=1:length(b)
 result(i,:) = find(a==b(i));
end
% result should be [2,9;4,8;5,7]
 the a and b in practice is very large (8000000). it takes long time in this for loop way. is there any way to improve the code?
i had tried to use ismember function. but it seems i could not bypass the find function.
[ia,ib] = ismember(a,b);
result = zeros(length(b),2);
for i=1:length(b)
 result(i,:) = find(ib==i);
end
i know i could use parallel computing toolbox. i just want a more delicated coding way.
>> [x,y] = ismember(a,b);
>> [~,z] = sort(y(x));
>> v = find(x);
>> r = reshape(v(z),2,[]).'
r =
 2 9
 4 8
 5 7
never mind, finally solved it. i called this.engine.runrenderloop while it’s already running, therefore causing the speed to run twice, because it added a loop/callback the 2nd time.

all i need to do for the ‘resume’ part of my function is to always call this.engine.stoprenderloop() before i call t… howdy and welcome to the forum!

take a closer look at the comment on line 13…it suggests using a different method

you are incrementing enemyindex, but not quite in the correct place…it should be the final statement in your while(enemyindex…) loop

like item 1, don’t forget the instructions in the c… You could achieve this with a simple `for` loop:



```
var min = 12,
    max = 100,
    select = document.getElementById('selectElementId');

for (var i = min; i<=max; i++){
    var opt = document.createElement('option');
    opt.value = i;
    opt.innerHTML = i;
    select.appendChild(opt);
}

```

[JS Fiddle demo](https://jsfiddle.net/davidThomas/NX3ac/).


[JS Perf](https://jsperf.com/) comparison of both mine and [Sime Vidas' answer](https://jsperf.com/comparison-of-loops), run because I thought his looked a little more understandable/intuitive than mine and I wondered how that would translate into implementation. According to Chromium 14/Ubuntu 11.04 mine is somewhat faster, other browsers/platforms are likely to have differing results though.







**Edited** in response to comment from OP:



> 
> [How] do [I] apply this to more than one element?
> 
> 
> 



```
function populateSelect(target, min, max){
    if (!target){
        return false;
    }
    else {
        var min = min || 0,
            max = max || min + 100;

        select = document.getElementById(target);

        for (var i = min; i<=max; i++){
            var opt = document.createElement('option');
            opt.value = i;
            opt.innerHTML = i;
            select.appendChild(opt);
        }
    }
}
// calling the function with all three values:
populateSelect('selectElementId',12,100);

// calling the function with only the 'id' ('min' and 'max' are set to defaults):
populateSelect('anotherSelect');

// calling the function with the 'id' and the 'min' (the 'max' is set to default):
populateSelect('moreSelects', 50);

```

[JS Fiddle demo](https://jsfiddle.net/davidThomas/NX3ac/1/).


And, finally (after quite a delay...), an approach extending the prototype of the `HTMLSelectElement` in order to chain the `populate()` function, as a method, to the DOM node:



```
HTMLSelectElement.prototype.populate = function (opts) {
    var settings = {};

    settings.min = 0;
    settings.max = settings.min + 100;

    for (var userOpt in opts) {
        if (opts.hasOwnProperty(userOpt)) {
            settings[userOpt] = opts[userOpt];
        }
    }

    for (var i = settings.min; i <= settings.max; i++) {
        this.appendChild(new Option(i, i));
    }
};

document.getElementById('selectElementId').populate({
    'min': 12,
    'max': 40
});

```

[JS Fiddle demo](https://jsfiddle.net/davidThomas/NX3ac/148/).


References:


* [`node.appendChild()`](https://developer.mozilla.org/en/DOM/node.appendChild).
* [`document.getElementById()`](https://developer.mozilla.org/en/DOM/document.getElementById).
* [`element.innerHTML`](https://developer.mozilla.org/en/DOM/element.innerHTML). `for i in count:` means `for i in 7:`, which won't work. The bit after the `in` should be of an iterable type, not a number. Try this:



```
for i in range(count):

``` The existing solutions based on `findall` are fine for non-overlapping matches (and no doubt optimal except maybe for HUGE number of matches), although alternatives such as `sum(1 for m in re.finditer(thepattern, thestring))` (to avoid ever materializing the list when all you care about is the count) are also quite possible. Somewhat idiosyncratic would be using `subn` and ignoring the resulting string...:



```
def countnonoverlappingrematches(pattern, thestring):
  return re.subn(pattern, '', thestring)[1]

```

the only real advantage of this latter idea would come if you only cared to count (say) up to 100 matches; then, `re.subn(pattern, '', thestring, 100)[1]` might be practical (returning 100 whether there are 100 matches, or 1000, or even larger numbers).


Counting **overlapping** matches requires you to write more code, because the built-in functions in question are all focused on NON-overlapping matches. There's also a problem of definition, e.g, with pattern being `'a+'` and thestring being `'aa'`, would you consider this to be just one match, or three (the first `a`, the second one, both of them), or...?


Assuming for example that you want possibly-overlapping matches *starting at distinct spots in the string* (which then would give TWO matches for the example in the previous paragraph):



```
def countoverlappingdistinct(pattern, thestring):
  total = 0
  start = 0
  there = re.compile(pattern)
  while True:
    mo = there.search(thestring, start)
    if mo is None: return total
    total += 1
    start = 1 + mo.start()

```

Note that you do have to compile the pattern into a RE object in this case: function `re.search` does not accept a `start` argument (starting position for the search) the way *method* `search` does, so you'd have to be slicing thestring as you go -- definitely more effort than just having the next search start at the next possible distinct starting point, which is what I'm doing in this function. For the most part the code is pretty good. You made a few minor errors that would be expected since you are still starting out but you should really work on consistency in indentation since it is harder to read and edit (you will really notice this later on) so you should get into the habit of trying to make your code look nice early on.



  

I commented in a few places where I made changes.



```
#include <iostream>
#include <cstdlib> //needed for system() because not all compilers include this header by default

using namespace std;

//the way you are using your functions you can/should have them all return void
void getlist(int[], int&);
void putlist (const int[], int);
void mean_average (const int[], int);
void MinIndex (const int[], int);
void left_rotate (int[], int);

const int MAXSIZE = 50;

int main()
{
	int mylist[MAXSIZE];
	int num_items;

	getlist(mylist, num_items);
	putlist(mylist, num_items);
	MinIndex(mylist, num_items);
	mean_average(mylist, num_items);
	left_rotate(mylist, num_items);

	system ("PAUSE");
	return 0;
}

void getlist(int mylist[], int &num_items)
{
	cout << "Enter the number of Array Elements, Maximum " << MAXSIZE << endl;
	cin >> num_items;

	for( int i = 0; i < num_items; i++ )
	{
		cout << "Enter the next array element: ";
		cin >> mylist[i];
	}
	cout << endl;
}

void putlist(const int mylist[], int num_items)
{
	cout << endl << "Array elements\n";
	for( int i = 0; i < num_items; i++ )
	{
		cout << i << " " << mylist [i] << endl;
	}
}

void MinIndex(const int mylist[], int num_items)
{
	int min = 0; //assuming min index is 0 (not the actual value there)

	for( int i = 0; i < num_items; i++ )
	{
		if( mylist[i] < mylist[min] ) //compare the values at each index
			min = i;
	}

	cout << endl << "The address of the smallest number is " << min << endl;
}

void mean_average(const int mylist[],int num_items)
{
	int sum = 0;
	float average;

	for( int i= 0; i < num_items; i++ ) //use < if your are using num_items or <= if you use num_items-1
	{
		sum += mylist[i];
	}
	average = sum / num_items;

	cout << endl << "The average value is: " << average << endl;
}

//used a bit of your code but rewrote most of left_rotate (this seems more like a left shift)
void left_rotate(int mylist[], int num_items)
{
	int temp = mylist[0];
	for( int i = 0; i < num_items-1; i++ )
	{
		mylist[i] = mylist[i+1];
	}
	mylist[num_items-1] = temp;

	cout << endl << "The new array elements are:\n";
	for( int i = 0; i < num_items; i++ )
		cout << mylist[i] << " ";
	cout << endl << endl;
}
``` for this, just use an if function. see https://macmost.com/learn-how-to-use-the-if-function-in-numbers.html so something like this in a2: if(isblank(b2),c2,b2) the condition is to check if b2 is blank. if it is, get the value of c2. if it isn’t blank, then get the value of b2. method a.increment() overlaps in class b.   
 therefore, regardless of the type of the variable obj, will be called the method corresponding to the actual type of the object - that is, b.increment().  
 
this method will use the variable i, declared in the same class b and having an initial value of 10.  
 
the resulting value - 11. You need to give the user the option of typing in a value that represents that there are no more values to enter. Perhaps give a prompt like:



```
Please enter a value.  Enter -999999 if you have no more values [B]:[/B]
```

As for the ten (or fewer) values, you should probably have an array and a loop instead of ten separate variable names and ten separate cin statements. So you're looking at something like this:



```
double dValue[10];
    int numEntries = 0;
    double sum = 0;
    
    while (numEntries < 10)
    {
          cout << "Enter number (-999999 to stop) : ";
          cin >> dValue[numEntries];
          // check whether dValue[numEntries] == -999999
          // if so, short-circuit the loop with the "break" command
            
          // increment numEntries
          // adjust sum
    }
```

As a side note, I picked -999999 as the value to represent no more values because



1. It's an integer, so it can be represented exactly as a double (no round-off error using == to compare).
2. It's a number that, chances are, people wouldn't actually want to add, so it's sort of "out of the way". Chances are, few people want to add -999999. If they do, they can't use this program! Hi Valdeth. You should use input and output file streams if you want to write and read from a file. Basically you open the file for writing and once you are done close the file. Later you can open the file for reading. The example below reads numbers from the file and just prints them out. If you want to read the file line by line you should look at the getline() function. I have just used your initial array to come up with a result per array which gives the product of all negative numbers in the array. Note that there **HAS** to be at least 1 negative number per array.



```
const int m=4, n=5;
	int i,j;
	int num;
	int result;
	int A[m][n]={{5,3,-4,8,2},
				 {1,5,2,7,-8},
				 {-3,9,5,2,4},
				 {4,-1,3,6,8}};

	ofstream outfile;
	ifstream infile; 

	outfile.open("c:/matrix/matrix.txt");

	for (i=0;i<m;i++)
	{
		result = 1;

		for (j=0;j<n;j++)
		{
			outfile << setw(3)<< A[i][j];

                            // Multiply negative numbers in each array (has to be at least 1 negative number in each array)
			if (A[i][j] < 0)              				                      result *= A[i][j];  // result = result x A[i][j]
		}
		cout << "Result of array " << i << " is " << result << endl;
		outfile << "\n";
	}

	outfile.close(); // Close for writing

	infile.open("c:/matrix/matrix.txt"); // opens the file
    
	infile >> num;
	while ( !infile.eof() ) 
	{ // keep reading until end-of-file
		cout << "The next number is " << num << endl;
		infile >> num; // sets EOF flag if no value found
	}
	infile.close();  //Close for reading
```