How to get a summation of elements of a matrix in a loop?

Now I want to find a third matrix 'X' such that X(1)=A(1)
and also
X(i+1)= sum of A(i+1) - sum of B(i) - sum of X(i)
Thanks in advance.

 Accepted Answer

The most serious flaw in your code is the expression
(sum(A(:,i+1)))-(sum(B(:,i)))-(sum(X(:,i)))
These sums would be done down the columns as you write this, but your vectors are row vectors, so the 'sum' operator has nothing to add. The answers it gets are just those of single elements in each part.
Also the line
X(i)=X(i);
is useless since it merely copies the value in X(i) right back into itself.
You ought to be using X(i) = max(x(i),0) here rather then the if-then-else construct.
There is no point in executing X(1)=A(1) each time you go through the loop. It should be located prior to entering the loop.
My final objection is to your description: "only positive integers of X should be considered, if a value of x is negative it should be considered as zero". The impression you give there is that a number is always either negative or it is a positive integer, which of course is not true. Your answer of 3.3 for the second element of X above is not a positive integer and it is also not negative.
Here is my guess as to the code you are seeking:
n = size(A,2);
X = zero(1,n);
X(1) = A(1);
CA = cumsum(A);
CB = cumsum(B);
for ix = 2:n
X(ix) = max(CA(ix)-CB(ix-1)-sum(X(1:ix-1)),0);
end

More Answers (0)

Asked:

on 20 Nov 2013

Edited:

on 24 Nov 2013

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!