Reputation: 7486
I wrote the following code for convolution in Matlab, but it gives me errors at notified lines. I am a beginner in Matlab so please bear with me answering this question.
function [y] = UmerConv(x,h)
xlen=length(x);
hlen=length(h);
p=1;
for j=1:xlen
for k=1:hlen
uinput{p}=x(j)*h(k);
p=p+1;
end
end
for i=1:hlen
if(i==1 || i==hlen)
y{i}=uinput(i); // error
else
y{i}=uinput(i)+uinput(i+2); // error
end
end
Thanks
Upvotes: 1
Views: 58
Reputation: 77484
You assign values into uinput with cell array syntax {}
, but then later you index them with regular array syntax with uinput(i)
. You have to keep it consistent. Using the curly braces {}
makes the array a cell array, which is indexed differently than a regular array (which uses just parentheses).
You then also make the same assignment choice with the variable y
, using the cell array syntax when it seems you'll probably want just regular array syntax.
The corrected code should probably be:
function [y] = UmerConv(x,h)
xlen=length(x);
hlen=length(h);
p=1;
for j=1:xlen
for k=1:hlen
uinput(p) = x(j)*h(k); % <-- Changed the {} syntax
p=p+1;
end
end
for i=1:hlen
if(i==1 || i==hlen)
y(i) = uinput(i); % <-- Now you access both with () instead of {}
else
y(i) = uinput(i) + uinput(i+2); % <-- Same here.
end
end
At each place where I noted a correction in a comment, you could alternately stick with solely the {}
syntax, and then everything will work but the arrays will be cell arrays. Usually this is not desired for a such a numerical computation.
Upvotes: 2
Reputation: 10864
You should use y(i)
instead that y{i}
to access the i-th position of a vector.
Upvotes: 0