How could I do sumation of members of 1st column of matrix?

zakyn's picture

Hello,

I would like to use sum command to compute sum.

A := Matrix(3, 2, {(1, 1) = 1, (1, 2) = 2, (2, 1) = 2, (2, 2) = 3, (3, 1) = 3, (3, 2) = 4});
> sum(A[k, 1], k = 1 .. 3);

Error, bad index into Matrix

Why it occures an error? If I use sum over list, it works.

How can I sum members of 1st column of Matrix?

Thanks

Vladimir

Comments

add sum (again)

You are having a problem because of the way sum works, which is the way most Maple procedures work: it first evaluates its arguments. In this case, that means it evaluates A[k,1], which raises an error because one cannot supply a symbolic value as an index to an rtable. One way to get around this is to delay the evaluation of A[k,1]; you do that by enclosing it in forward quotes (see ?uneval):

 A := Matrix(3,2,(i,j)->i+j-1);
                                      [1    2]
                                      [      ]
                                 A := [2    3]
                                      [      ]
                                      [3    4]
sum('A[i,1]',i=1..3);
                                 6

A better way to handle this is to use the Maple add procedure; it uses special evaluation rules (see ?spec_eval), that is, its first argument is not evaluated initially:

add(A[i,1], i=1..3);
                                 6

That is better for two reasons: (1) it is simpler (less typing, no quotes), and (2) it uses a builtin procedure designed for adding explicit sequences, rather than a procedure (sum) intended for computing symbolic summations (see the note in ?sum). You could also do

add(i, i=A[1..-1,1]);

which avoids the issue but isn't quite as efficient since it extracts a column of the Matrix before adding. A less obvious method is to use rtable_scanblock:

rtable_scanblock(A, [1..3,1], Sum);
                                  6

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
}