Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

Topic: sum all elements of a cell array
Replies: 19   Last Post: Apr 25, 2012 6:10 AM

 Messages: [ Previous | Next ]
 Matt J Posts: 4,997 Registered: 11/28/09
Re: sum all elements of a cell array
Posted: Apr 24, 2012 10:46 AM

This might just add to the confusion, but here's a totally different way

[ii,jj]=ndgrid(1:3,1:3);
p=[ii(:).';jj(:).'];

R=interdists(p);

B=reshape(sum(R),3,3);

which uses the following utility

function Graph=interdists(A,B)
%Finds the graph of distances between point coordinates
%
% (1) Graph=interdists(A,B)
%
% in:
%
% A: matrix whose columns are coordinates of points, for example
% [[x1;y1;z1], [x2;y2;z2] ,..., [xM;yM;zM]]
% but the columns may be points in a space of any dimension, not just 3D.
%
% B: A second matrix whose columns are coordinates of points in the same
% Euclidean space. Default B=A.
%
%
% out:
%
% Graph: The MxN matrix of separation distances in l2 norm between the coordinates.
% Namely, Graph(i,j) will be the distance between A(:,i) and B(:,j).
%
%
% (2) interdists(A,'noself') is the same as interdists(A), except the output
% diagonals will be NaN instead of zero. Hence, for example, operations
% like min(interdists(A,'noself')) will ignore self-distances.
%

noself=false;
if nargin<2
B=A;
elseif ischar(B)&&strcmpi(B,'noself')
noself=true;
B=A;
end

N=size(A,1);
B=reshape(B,N,1,[]);

Graph=l2norm(bsxfun(@minus, A, B),1);

Graph=squeeze(Graph);

if noself
n=length(Graph);
Graph(linspace(1,n^2,n))=nan;
end

Date Subject Author
4/23/12 arron
4/23/12 Matt J
4/23/12 arron
4/23/12 ImageAnalyst
4/23/12 arron
4/23/12 arron
4/23/12 Matt J
4/23/12 arron
4/23/12 ImageAnalyst
4/24/12 arron
4/24/12 ImageAnalyst
4/24/12 arron
4/24/12 Matt J
4/24/12 Matt J
4/24/12 arron
4/24/12 Matt J
4/24/12 ImageAnalyst
4/25/12 arron
4/25/12 ImageAnalyst
4/23/12 ImageAnalyst