I want to know how to speed up my for loop,it's a simple for loop.thanks
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
ang lee
am 22 Okt. 2019
Kommentiert: ang lee
am 23 Okt. 2019
%% 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 Kommentare
Akzeptierte Antwort
Daniel M
am 22 Okt. 2019
Bearbeitet: Daniel M
am 22 Okt. 2019
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 Kommentare
Daniel M
am 23 Okt. 2019
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)));
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!