# Thread Subject: Summing in Multi Dimensions

 Subject: Summing in Multi Dimensions From: james bejon Date: 10 Apr, 2010 23:18:07 Message: 1 of 5 I'm probably missing something obvious here, but suppose I have the following r = rand(4, 5, 3, 9, 10); and I want to create, say, a (1 x 5 x 1 x 9) matrix by summing dimensions 1, 3 and 5. I thought something like sum(r, [1, 3, 5]) might do the job. But it doesn't. And sum(sum(sum(r, 1), 3), 5) seems a bit clumsy. Any suggestions?
 Subject: Summing in Multi Dimensions From: Matt J Date: 11 Apr, 2010 09:19:03 Message: 2 of 5 "james bejon" wrote in message ... > I'm probably missing something obvious here, but suppose I have the following > > r = rand(4, 5, 3, 9, 10); > > and I want to create, say, a (1 x 5 x 1 x 9) matrix by summing dimensions 1, 3 and 5. I thought something like > > sum(r, [1, 3, 5]) > > might do the job. But it doesn't. And > > sum(sum(sum(r, 1), 3), 5) > > seems a bit clumsy. Any suggestions? Why not just create your own function which enables the first syntax sumdims(r,[1,3,5]) function out=sumdims(r,dims)  out=r; for i=1:length(dims)  out=sum(out,dims(i)); end
 Subject: Summing in Multi Dimensions From: james bejon Date: 11 Apr, 2010 13:02:04 Message: 3 of 5 Hi Matt. Yeah, I could do. Cheers for the suggestion. I just thought there'd be a built-in way that I was missing. Plus, I'm keen on avoiding for loops, though I suppose I could just do what you've done using arrayfun...
 Subject: Summing in Multi Dimensions From: John D'Errico Date: 11 Apr, 2010 13:17:02 Message: 4 of 5 "james bejon" wrote in message ... > Hi Matt. Yeah, I could do. Cheers for the suggestion. I just thought there'd be a built-in way that I was missing. Plus, I'm keen on avoiding for loops, though I suppose I could just do what you've done using arrayfun... Permute. Then a reshape. Then a single call to sum will do it. John
 Subject: Summing in Multi Dimensions From: Matt J Date: 11 Apr, 2010 13:30:05 Message: 5 of 5 "james bejon" wrote in message ... > Hi Matt. Yeah, I could do. Cheers for the suggestion. I just thought there'd be a built-in way that I was missing. Plus, I'm keen on avoiding for loops, though I suppose I could just do what you've done using arrayfun... =========== I'd be surprised if anything is faster than the for-loop.

### Everyone's Tags:

Separated by commas
Ex.: root locus, bode

### What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.