the convolution function i wrote doesn't work for the big arrays

1 view (last 30 days)
i have this homework where i have to write my own convolution function for discrete time on matlab, which i had but it only works great with small data. i also have to record my voice and get it convoluted with my own function but it gives 'the variable changes in size error' and then keeps running without plotting anything. i don't really want the solution itself, i just would really appreciate it if someone just walks me through the problem and guides me on how to solve it. thank you in advance.
x1 and h should be convoluted, in the code.
recObj = audiorecorder; %%
disp('Start speaking.') %%
recordblocking(recObj, 5); %%
disp('End of Recording.'); %%
x1 = getaudiodata(recObj); %%
x1=permute(x1,[2 1]);
m=2; %% creating the h function.
h=zeros([1 400*m]);
j=1;
a=0.8;
h(1)=1;
for i=400:400:(400*m)
h(i)=a*j;
j=j+1;
%indexes for the x1 function.
end
inX=[];
for i=1:1:40000
inX(i)=i;
end
%indexes for the h function
inH=[];
for i=1:1:400*m
inH(i)=i;
end
tempY=inH;
y1=myConv(x1,40000,h,400*m,inX,inH,tempY);
stem(y1);
% convolution function
function result=myConv(x,n,y,m,inX,inY,tempY)
% calculating the convolution array's length
newLength=m+n-1;
% calculating the y(-m)
for i=1:1:m
tempY(i)=inY(i)*(-1);
tempY(i)=tempY(i)+inX(1)+inY(1);
end
% calculating convolution
c=1;
while c<=newLength
result(c)=0;
for i=1:1:n
for j=1:1:m
if inX(i)==tempY(j)
result(c)=result(c)+(x(i)*y(j));
end
end
end
c=c+1;
for i=1:1:m
tempY(i)=tempY(i)+1;
end
end
end
  1 Comment
Jan
Jan on 21 Nov 2022
"it gives 'the variable changes in size error'" - please post a copy of the complete message and mention, in which line the error occurs. A rough paraphgrasation is not useful.
This is a waste of time:
inX=[];
for i=1:1:40000
inX(i)=i;
end
%indexes for the h function
inH=[];
for i=1:1:400*m
inH(i)=i;
end
Much faster:
inX = 1:40000;
inH = 1:400*m;
The iterative growing of arrays is extremly expensive: in each iteration a new array is created and the old data are copied.

Sign in to comment.

Answers (1)

Jan
Jan on 21 Nov 2022
Pre-allocation is important, if you work with large arrays. Example:
x = [];
for k = 1:1e6
x(k) = k;
end
In each iteration a new array is created and the former values are copied. Therefore Matlab allocates sum(1:1e6)*8 bytes with the above code, which is more than 4 TB, although the final array has a size of 8 MB only.
The solution is easy: Create the array with the final size at first:
x = zeros(1, 1e6);
for k = 1:1e6
x(k) = k;
end
Now Matlab allocates 8 MB only.
Working with arrays is more efficient than processing the elements in a loop:
for i=1:1:m
tempY(i)=inY(i)*(-1);
tempY(i)=tempY(i)+inX(1)+inY(1);
end
% Nicer and faster without a loop:
tempY(1:m) = inX(1:m) + inY(1:m) - inY(1);

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!