MATLAB: Setting up vector function

setting up vectorsvectors

I write a function SetUp to set up three vectors from an input vector k. Vector c = (-k(2); -k(3); ….. -k(n)) where I have n-1 elements. Vector d = (k(1)+k(2); k(2)+k(3); …… k(n-1)+k(n); k(n)) where there are n elements And vector e = vector c.
Here is the code I wrote:
function [c,e,d] = SetUp
k = input('Enter k vector');
n = size(k,2);
for k1 = 1:n
c = -k(k1)*ones(n-1,1);
d = (k(k1)+k(k1+1))*ones(n,1); d(n) = k(n);
e = c;
end
end
By running this code I get an error: Index exceeds matrix dimensions.
Problem is in this line: d = (k(k1)+k(k1+1))*ones(n,1); d(n) = k(n);
In my opinion the problem is in indexing as the last term when Matlab runs d = (k(k1)+k(k1+1))*ones(n,1); is d = k(n)+k(n+1), where the program does not recognize k(n+1) as there is no such term in vector k.
So, the question is, how to overcome this problem as I don't even need the last term as the last term is d(n) = k(n)???
Thanks in advance!

Best Answer

In your for loop, you are using k(k1+1). if k1 is the last element of k, then k(k1+1) will be exceeding the dimension of k. If you dont care about the last term, use
for k1 = 1:n-1
... Stuff ...
end
d(n) = k(n);
or if you need the other vectors to go to n, stick it in a conditional
for k1 = 1:n
... Other Stuff ...
if k1~=n
d = (k(k1)+k(k1+1))*ones(n,1);
end
end