MATLAB Answers

Summing nonsequential elements in a matrix

조회 수: 1(최근 30일)
AJ
AJ 15 May 2013
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.

  댓글 수: 0

댓글을 달려면 로그인하십시오.

채택된 답변

Cedric Wannaz
Cedric Wannaz 15 May 2013
편집: Cedric Wannaz 15 May 2013
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

  댓글 수: 1

AJ
AJ 17 May 2013
Thank you both for your answers. It was a silly error on my part

댓글을 달려면 로그인하십시오.

추가 답변(1개)

Thomas
Thomas 15 May 2013
works just fine
a=magic(5)
a =
17.00 24.00 1.00 8.00 15.00
23.00 5.00 7.00 14.00 16.00
4.00 6.00 13.00 20.00 22.00
10.00 12.00 19.00 21.00 3.00
11.00 18.00 25.00 2.00 9.00
sum(a(1,[3 5]))
ans =
16.00
which is the sum of a(1,3) =1 and a(1,5)=15 , total=16

  댓글 수: 0

댓글을 달려면 로그인하십시오.

태그

Community Treasure Hunt

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

Start Hunting!

Translated by