Understanding Matrix Notation/Arithmetic
6 views (last 30 days)
Show older comments
I am a Matlab newbie, so please be gentle.
I am attempting to port some Matlab code to C++ and am not following some of the syntax.
Here is the code I am porting:
[ndata, dimx] = size(x);
[ncentres, dimc] = size(c);
if dimx ~= dimc
error('Data dimension does not match dimension of centres')
end
n2 = (ones(ncentres, 1) * sum((x.^2)', 1))' + ...
ones(ndata, 1) * sum((c.^2)',1) - ...
2.*(x*(c'));
In this code, x and c are both two dimensional matrices, each with two columns and many rows.
I am getting lost on the n2 line.
Focusing on the clause: "sum((x.^2)',1))'".
I believe that squares every element in the x matrix.
Then transpose the matrix (resulting in a 2xN matrix).
Then sum each column of the matrix (resulting in a 1xN matrix).
Then transpose again (resulting in a Nx1 matrix).
Is this correct?
Thanks for any help.
0 Comments
Accepted Answer
Jan
on 22 Feb 2017
Edited: Jan
on 22 Feb 2017
Almost. You need the first part also:
(ones(ncentres, 1) * sum((x.^2)', 1))'
sum((x.^2)', 1) this is: square elements, transpose, sum over 1st dimension.
Then it is mutliplied with a [M x 1] matrix consisting of 1s from the right and transposed afterwards. Shorter (and faster):
sum(x.^2, 2) * ones(1, ncentres)
The multiplication repeates the columns only, so this is equivalent to:
repmat(sum(x.^2, 2), 1, ncentres)
0 Comments
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!