convolution in matlab using for loop

Status
Not open for further replies.

Ibaghdadi

Newbie level 6
Joined
Dec 26, 2007
Messages
12
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,281
Location
Lebanon
Activity points
1,387
for loop matlab

Hi;
I want to use the convolution in matlab, using for loop so i did the following:
Code:
n=6;
x=[1 2 2 3];
h=[2 -1 3];
y=zeros(1,n);
for i=0:n
for j=0:i
y(j)=y(j)+x(j)*h(i-j);
end
end

that did not work and I got the following error:
Code:
??? Subscript indices must either be real positive integers or logicals.

why?

Added after 45 minutes:

ok i found a huge problem in my code which is mostly i am starting the index in zero not in 1 so i did the following:

Code:
 n=6;
x=[1 2 2 3];
h=[2 -1 3];
y=zeros(1,n);
for i=1:n
for j=1:i
y(i)=y(i)+x(j)*h(i-j+1)
end 
end

now i get a new error:
??? Index exceeds matrix dimensions.
 

Your program is on the right track, but the problem is your are trying to access elements of x which do not exist, i.e x(5) and so on.

So to avoid this problem adjust the length of x and h to be equivalent to the final length as shown:-

n=6;
x=[1 2 2 3 0 0];
h=[2 -1 3 0 0 0];
y=zeros(1,n);
for i=1:n
for j=1:i
y(i)=y(i)+x(j)*h(i-j+1)
end
end

So both x and h are now of length 6.

Another option would be to take x and h and then later append zeroes to it to make their lengths equal to 6, such as:-

n=6;
x=[1 2 2 3];
h=[2 -1 3];
x=[x zeros(1,6-length(x))];
h=[h zeros(1,6-length(h))];
y=zeros(1,n);
for i=1:n
for j=1:i
y(i)=y(i)+x(j)*h(i-j+1)
end
end


Hope this was helpful...
 

Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…