How can i reduce the time that take my code to run?

1 次查看(过去 30 天)
Hello, i've been doin this code for a class, but is takes arround 180 seconds to run, i want to know if there is any way to optimize it, i think the "for loop" is taking so many time.
Ts=1/44100;
Fs=1/Ts;
t=0:Ts:3-(Ts);
y=sin(2*pi*440*t); % 440=La.
%sound(y,Fs);
%pause(3)
ynoise=y+(0.1).*randn(size(y));
%sound(ynoise,Fs);
ynoise(randi(length(y),1,ceil(0.01*length(y))))=randi(3)-2; q
%pause(3)
yx=ynoise;
N=10;
w=cat(2,zeros(1,(N-1)),yx);
un=cat(2,ones(1,N),zeros(1,length(y)-1));
h=zeros(1,(length(y)));
for i=1:length(y)
h(i)=sum(w.*un)/N;
un=circshift(un,1);
end
figure(1)
subplot(2,2,1),plot(t(1:300),y(1:300)),title("La")
subplot(2,1,2),plot(t(1:300),h(1:300)),title("new")
subplot(2,2,2),plot(t(1:300),ynoise(1:300)),title("La + noise")

回答(1 个)

Luna
Luna 2018-10-6
try parallel for loop instead of your for loop. It took 109 secs in my machine.
parfor i=1:length(y)
newun=circshift(un,1);
h(i)=sum(w.*newun)/N;
end

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by