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

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

Post by Stefan Be » Tue, 07 Apr 2009 23:00:19

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 ..
thanks in advance

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

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

Post by Matt » Wed, 08 Apr 2009 00:06:02


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

It cna be done this way

Distances=norm( pos(I(:),:)-pos(J(:),:) )


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

Post by Matt » Wed, 08 Apr 2009 00:23:01

Make that

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