## 2d-matrix = sum( 3d-matrix , dim )

### 2d-matrix = sum( 3d-matrix , dim )

Hello everyone

I just encountered two problems at once. First of all I want to calculate the sum of a 3d-matrix with respect to one dimension! Unfortunately the sum only seems to work with 2d-matrices.
The second problem is a mathematical problem. I am pretty sure that it's possible to change a n x m x 1 matrix to an n x m x p matrix by multiplying it with something else. Since I could not figure it out I used a loop, but I guess that's not very effective if I want to use this part multiple times
My program is as follows:

syms a b c d e f
pos=[a b;c d;e f]; % x,y

[np,nd]=size(pos); %number of points, number of dimensions
for k1=1:np; pos1(k1,:,:)=pos'; pos2(:,:,k1)=pos; end % OPTIMIZE !!

(pos1-pos2).^2 % here it is a 3x2x3 matrix
sum( (pos1-pos2).^2 ,2) % here it is a 3x1 vector

I would really appreciate your help ..
stefan

(the whole point of this program is to calculate the distances between all points given in pos)

### 2d-matrix = sum( 3d-matrix , dim )

---------

What makes you say that? sum(X,3) should work fine

It cna be done this way

[I,J]=ndgrid(1:np,1:np);
Distances=norm( pos(I(:),:)-pos(J(:),:) )

### 2d-matrix = sum( 3d-matrix , dim )

Make that

Distances=sum( (pos(I(:),:)-pos(J(:),:)).^2, 2 )