What does (Theta2(:, 2:end).^2, 2)
mean?
p = sum(sum(Theta1(:, 2:end).^2, 2))+sum(sum(Theta2(:, 2:end).^2, 2));
What does (Theta2(:, 2:end).^2, 2)
mean?
p = sum(sum(Theta1(:, 2:end).^2, 2))+sum(sum(Theta2(:, 2:end).^2, 2));
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
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:
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.