-3

What does (Theta2(:, 2:end).^2, 2) mean?

p = sum(sum(Theta1(:, 2:end).^2, 2))+sum(sum(Theta2(:, 2:end).^2, 2)); 
Don
  • 3,876
  • 10
  • 47
  • 76
Sudarshan
  • 1
  • 2
  • Both the MATLAB and Octave tag guides say "Questions should be tagged with either [matlab] or [octave], but not both, unless the question explicitly involves both packages." This is the text that is shown when you select the tags to add to your question. Also, please read [ask]. – Cris Luengo Jan 08 '19 at 17:46
  • The code excerpt in the OP title is a syntax error. The "2" before the closing bracket is the second argument to the [`sum()`](https://www.mathworks.com/help/matlab/ref/sum.html) function and indicates that the sum should be computed for every row of the matrix in the first argument. The first argument means: Take all rows of `Theta1` and all columns, beginning from the second, and square the elements individually. – applesoup Jan 08 '19 at 17:47

2 Answers2

0

Let's start from the most inner parentheses. First, Theta1(:, 2:end).^2 maintains all the columns of Theta1 except the first one then squares it. Let denote the result with mem1. Then after, sum(mem1,2) computes the column sum whose output is the sum of all the columns of mem1 and therefore is a column itself. (sum(mem1,1) or sum(mem1) computes the row sum). Then sum(sum(mem1,2)) computes the summation of elements of sum(mem1,2) which finally yields to the sum of all elements of Theta1 squared. The same is true for Theta2.

P.S. You can simply use p = sum(sum(Theta1(:, 2:end).^2+Theta2(:, 2:end).^2)); as the result is the same

Mostafa Ayaz
  • 480
  • 1
  • 7
  • 16
0

Let's say we have a matrix theta2 of size (3,3) and we want to calculate the above expression that you've given which is sum(sum(Theta2(:, 2:end).^2, 2)). First of all let's break the expression:

  1. theta2(:,2:end).^2 --> choose all rows(which is shown by ':' instead of any row number) but choose the columns greater than equal to 2 and square each term.

2.sum(theta2(:,2:end).^2,2) --> sum the squares column wise.

3.sum(sum(theta2(:,2:end).^2,2)) --> Now, sum the resulting sum from the sum obtained by second step.

Abhishek
  • 113
  • 3
  • 12