MATLAB: How to fix this

error

I'm getting error:
Error in three (line 5) a(k+1) = a(k) + b(k);
function out = three(a,b,N)
a(1) = a;
b(1) = b;
for k = 1:N-1
a(k+1) = a(k) + b(k);
end
end

Best Answer

The only way that
b(1) = b;
could have succeeded is if length(b) matched length(b(1)) which can only occur if b was passed as a scalar. Likewise, the line above that could only succeed if a starts as a scalar.
But then in the loop you do
a(k+1) = a(k) + b(k);
On the first iteration, that is
a(2) = a(1) + b(1)
and that is okay because we know that a and b are both length 1 (or the lines above would have failed.) This extends a to length 2 so after the first iteration, a would be length 1 and b would still be length 1.
Then in the second iteration the loop would be
a(3) = a(2) + b(2)
and we created a(2) at the previous line. But b is still only length 1 so b(2) does not exist so this must fail.