## How to accelerate my code

on 14 Oct 2019

### darova (view profile)

on 14 Oct 2019
Hi, guys. The question I am asked to solve is like this. I will be given a list of numbers (note that the first and last numbers of this list will be equal and will be the maximum number in this list). In first step, I am asked to delete all the numbers whose value is between or equal to its adjcent numbers. For example, if the list given is [2 -1 -3 -3 2]. First -1 will be delte since its value is between 2 and -3. Then -3 will be delerte since there is another -3 on the side of it. The final list will be [2 -3 2]. Similaly, the second step asks to delte 2 numbers out of 4 if both the 2nd and 3rd numbers' value is in the middle or equal to 1st and 4th number. For example, if the list is [2 -1 -2-3]. -1 and -2 will be delete. And finally, I am asked to output the index of the numebs I delete in the second step.(Note that, the index number number should come from the very first list, not list after edit). I paste my code below. It works but will take 140s. The while loops took a lof of time to run. I am wondering if there is anyway to accelerate my code like avoiding using while loop. Thank you for your guys help. Really apperciate it.
clear all; close all; clc;
N = N';
len = length(N);
B= 1:len;
judge = 1;
while judge == 1
judge = 0;
for i = 1 : len-2
if (N(i+1)-N(i+2)) * (N(i+1)-N(i)) <= 0
N=[N(1:i),N(i+2:len)];
B=[B(1:i),B(i+2:len)];
judge = 1;
break
end % if
end % for
len = length(N);
end % while
A = N;
len = length(A);
%%
m = 1;
judge = 1;
file = fopen('ans.dat','w');
while judge == 1 && len >= 4
for i = 1:(len-3)
judge = 0;
if (A(i+1)-A(i))*(A(i+1)-A(i+3)) <= 0 && (A(i+2)-A(i))*(A(i+2)-A(i+3)) <=0
if A(i+1)<=A(i+2)
C(m) = B(i + 1);
C(m + 1) = B(i + 2);
else
C(m) = B(i + 2);
C(m + 1) = B(i + 1);
end % if
fprintf(file,'%8d %8d\t\n', C(m),C(m+1));
A = [A(1:i),A(i+3:len)];
B = [B(1:i),B(i+3:len)];
m = m + 2;
judge=1;
break
end % if
end % for
len = length(A);
end % while

darova

on 14 Oct 2019
Attach the data
Rongyu Chu

on 14 Oct 2019
Here is the data

### Rongyu Chu (view profile)

on 14 Oct 2019

Is there anyway I can use matrix instead of loops ? Matrix should be able to solve this much faster.

on 14 Oct 2019