Info

此问题已关闭。 请重新打开它进行编辑或回答。

How to accelerate my code

1 次查看(过去 30 天)
Rongyu Chu
Rongyu Chu 2019-10-14
关闭: MATLAB Answer Bot 2021-8-20
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 = load('expp.dat');
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

回答(2 个)

Rongyu Chu
Rongyu Chu 2019-10-14
Is there anyway I can use matrix instead of loops ? Matrix should be able to solve this much faster.

darova
darova 2019-10-14
What about findpeaks()?
X = load('datat.txt');
X1 = X(1:100);
[~,ix1] = findpeaks(X1);
[~,ix2] = findpeaks(-X1);
plot(X1,'.-b')
hold on
plot([ix1; ix2],X1([ix1; ix2]),'or')
hold off

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by