As it is said in the title, I'd like to find the previous position(not the last position) in an array where a value is met. I have a program that works but I'm looking for improvement or optimazations of my program.
To be specific, let's suppose I have an array A=[1 0 1 0 0 0 0 1 1 1 0 0 0 0 1] and I'd like to fill in values in another array B based on values in A.
The rule is, if A(i)=1, then B(i)=1;
if A(i)=0, find the index of the previous element in A which is 1, and compute the difference between that index and current index number. If the difference is larger than 1 and no larger than 3, B(i)=2; otherwise B(i)=0;
For example, when i=5, the index of previous element in A which is 1 is 3, then 5-3=2<3, so B(5)=2; when i=7, the index of previouse element in A which is 1 is 3, then 7-3=4>3, so B(7)=0;
So in the end, I hope to have an array B=[1 0 1 0 2 2 0 1 1 1 0 2 2 0 1];
Here is what my current program looks like
A=[1 0 1 0 0 0 0 1 1 1 0 0 0 0 1];
if i-find(B==1,1,'last')>1 && i-find(B==1,1,'last')<=3
The program works well. However the thing is, in future calculations, the length of array A could be as large as 1.5million and there will be some other calculations with indefinite amount of elements in the inner loop. So it's really time-comsuming to execute this find command in each iteration(last time I tried, it took 8hrs to compute for 500000 data points).
I tried to break the program into two one-layer-if-statements by allocating zero value to all data that satisfies the conditon in the inner loop and start another loop through them to find for which element I should specify 2 instead of 0. However, the problem is, the command find(X,n,direction) could only find the last position of an array where a value is met. So it always returns number 15 as it is the last position where value 1 appears in array A. I'm wondering, is there any other command that finds the index of the previous position where a value is met? For example, when i=5, the command would return number 3 while when i=11:14, it would return 10?