Sum of an arrays elements

I have an assigntment which sounds like this:
square each element in C and determine the sum of all C's elements
How do i do this? I don't get the right result, that i am supposed to get.

 Accepted Answer

Mischa Kim
Mischa Kim on 23 Feb 2014
Edited: Mischa Kim on 23 Feb 2014
I'd assume
C = [1 2 3];
res = sum(C.^2)
What is the input, what is the expected result?

9 Comments

It does not give me the correct result, as i've already tried that.
What is the input (vector), what is the expected result?
This is the array i have
C =
10 12 15 4 5 6 0 8 9 10
7 9 13 14 8 16 0 10 7 20
31 32 33 34 35 36 0 15 13 40
according to te book, the result should be 1391
Looking at the numbers, squaring only the last number, 40^2 = 1600, results in a number that is greater than the expected result. So there is a couple of options:
  • We don't exactly understand the problem statement.
  • The expected result (1391) is incorrect.
Yes you are right, and i can now see my mistake. thank you though! :)
We can see that for given matrix,result can't be 1391.
i made a mistake in making the array - so the correct array is this:
C =
10 12 15 1 1 1 0 1 1 1
7 9 13 1 1 1 0 10 7 1
1 1 1 1 1 1 0 15 13 1
But for some reason i dont get the right result. The result is way better then the one before.
I'll just for a safty, write down the assignment, maybe you can se what i am doing wrong.
a) write down the matrix A=[10 12 15; 7 9 13] b)use A to get the transponated matrix. c) write a matrix, C with 4 rows, and 10 columns, all with ones. d)set the element in C's 2 row, 5 column as 8. e) set the whole 7 column in C as 0 f)insert A in C on row 1 and 2 and column 1 to 3, g) insert B in C so C's element in row 2 and column 8 becomes 10. h) remove row 3 in C. i) square each element in C and determine the sum of all C's elements - 1391 is the result.
A = [10 12 15; 7 9 13];
B = A';
C = ones(4,10);
C(2,5) = 8;
C(:,7) = zeros(4,1);
C(1:2,1:3) = A;
C(2:4,8:9) = B;
C(3,:) = [];
sum(sum(C.^2))
ans =
1391
Hmm weird, that was pretty much what i was doing, but at least now i get the same result.
Thnak you :)

Sign in to comment.

More Answers (1)

Rasmus,entered matrix is wrong again! I get this fact from your description. Your matrix is - C =
10 12 15 1 1 1 0 1 1 1
7 9 13 1 8 1 0 10 7 1
1 1 1 1 1 1 0 15 13 1
Any way,I think this is what you want :
A = C.^2; Ans = sum(A(:));
For understanding purpose,see effect of A(:).
Note : For 2-dimentional matrix A, sum(sum(A)) is same as sum(A(:)).
Read help about 'sum()' in MATLAB help.

Categories

Find more on Operators and Elementary Operations in Help Center and File Exchange

Asked:

on 23 Feb 2014

Commented:

on 23 Feb 2014

Community Treasure Hunt

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

Start Hunting!