Reputation: 189
I want to calculate the variable h with the following system of equation in MATLAB. What could be a proper way to write it?
h(1) = 1 - z(1);
h(2) = 1 - h(1) - z(2);
h(3) = 1 - h(1) - h(2) - z(3);
h(4) = 1 - h(1) - h(2) - h(3) - z(4);
h(5) = 1 - h(1) - h(2) - h(3) - h(4) - z(5);
h(6) = 1 - h(1) - h(2) - h(3) - h(4) - h(5) - z(6);
Upvotes: 1
Views: 57
Reputation: 65460
You can accomplish this with diff
which takes the difference between any two elements.
z = [1 4 5 7 8 3];
h = [0 -diff(z)];
% 0 -3 -1 -2 -1 5
How we determine to use diff
is that we can easily write out the terms and see that most things cancel
h(2) = 1 - h(1) - z(2)
h(2) = 1 - (1 - z(1)) - z(2)
h(2) = 1 - 1 + z(1) - z(2)
h(2) = z(1) - z(2)
Upvotes: 4
Reputation: 2919
The below code should mostly work. The trick is to setup an array with z in it.
h=[]% empty array
h(1)=1-z(1)
for counter=2:N
h(counter)=1-cumsum(diff(h(1:counter-1)))-z(counter)
end
Upvotes: 0