I want to know how to speed up my for loop,it's a simple for loop.thanks

조회 수: 1 (최근 30일)
ang lee
ang lee 2019년 10월 22일
댓글: ang lee 2019년 10월 23일
%% this code cost aroud 6s.
b=[]; %Establish a null matrix
N=length(ampw_1); % N=103;
M=length(amp_m); % M=512;
for j = 1:M-N+1; % j=1:1:410;
index_sm = j; %index_sm = 1:410;
index_em = j+N-1; %index_em = 103:512;
ampw_2 = abs(amp_m(index_sm:index_em))/max(abs(amp_m(index_sm :index_em))); %ampw_2 from 1 to 103; from 2 to 104; from 3 to 105....from 410 to 512
% Every loop,this segment will store 103 * 1 So,the At the end of the loop,the ampw_2 array is 103 * 410 and give b array.In my program, this statement took 4S,and i want to know how to speed it up.
b = [b ampw_2]; %give the result of every loop to b,at the end of the loop , the b array is 103*410;
end
%% then I I built an empty array,the code as follow,But it's only a few seconds shorter,just 0,4s.
N=length(ampw_1); %N=103
M=length(amp_m); %M=512
ampw_2 = zeros(N,M-N+1); %Set up a zero array of 103 * 410;
for j = 1:M-N+1; % j=1:1:410;
index_sm = j; %index_sm = 1:410;
index_em = j+N-1; %index_em = 103:512;
ampw_2(:,j) = abs(amp_m(index_sm:index_em))/max(abs(amp_m(index_sm :index_em)));
end
%% I want to know is there Any method to speed up the program,then I use the matlabpool open 2;this code cost So More time,it's 60s; Just modify:
parfor j=1:M-N+1;
....
end
if you have any method or proposal,please tell me , thank you very much,
  댓글 수: 2
Daniel M
Daniel M 2019년 10월 22일
You don't need to do this in a loop at all.
ang lee
ang lee 2019년 10월 22일
Can you be more specific,or for a simple example,I can't run the code you gave me.thank you again

댓글을 달려면 로그인하십시오.

채택된 답변

Daniel M
Daniel M 2019년 10월 22일
편집: Daniel M 2019년 10월 22일
You don't need to do this in a loop at all. Here is how to vectorize the creation of the indices from 1:103, ..., 410:512. From there you can probably figure out how to do it without using a loop at all. (Assuming amp_m is a variable and not a function).
n = 103;
m = 410;
indexMatrix = (0:n-1)'+(1:m);
  댓글 수: 5
Daniel M
Daniel M 2019년 10월 23일
You must have an older version of MATLAB that can't do implicit expansion. Here is the fix for that line of code. Tell me if there are other errors.
indexMatrix = bsxfun(@plus,(0:N-1)',(1:(M-N+1)));
ang lee
ang lee 2019년 10월 23일
thank you, I can use this code in other version,and your answer is so good.Help me a lot.If I have other question,i hope i can ask you . thank you again,best wishes.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by