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

1 次查看(过去 30 天)
%% 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,

采纳的回答

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