MATLAB: Summing nonsequential elements in a matrix

matrixsortsum

Sorry if this is a very simple question, but how would I go about finding the sum of a set of predetermined elements in a matrix. So if I was using
a=magic(50),
I found that my idea of using the command
x = sum(a, (1, [5 7 19 33 34 35 36 47 50]))
does not provide the output (the sum of the elements in those positions) that I wanted. I would appreciate any help.

Best Answer

magic(50) is a square, 50x50 matrix. What do you want to achieve? Is it summing elements [5 7 19 33 34 35 36 47 50] of row 1 of a? If so, you'll want to do
s = sum( a(1,[5 7 19 33 34 35 36 47 50]) )
If you are unsure, work with smaller objects that can be easily displayed, e.g.
>> a = magic(5)
a =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
>> s = sum( a, (1, [2,4,5])) % First idea, is it right?
s = sum( a, (1, [2,4,5]))
|
Error: Expression or statement is incorrect--possibly unbalanced (, {, or [.
>> a(1,[2,4,5]) % Let's see if we can at least access the
% correct set of elements before summing.
ans =
24 8 15
>> s = sum( a(1,[2,4,5]) ) % Let's see if we can sum them now.
s =
47