I want to know how to speed up my for loop,it's a simple for loop.thanks
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
ang lee
el 22 de Oct. de 2019
Comentada: ang lee
el 23 de Oct. de 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 comentarios
Respuesta aceptada
Daniel M
el 22 de Oct. de 2019
Editada: Daniel M
el 22 de Oct. de 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 comentarios
Daniel M
el 23 de Oct. de 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)));
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!