Re: Operating on multi-dimensional arrays
- From: Arthur G <gorramfreak+news@xxxxxxxxx>
- Date: Thu, 21 Feb 2008 13:59:25 -0500
On 2008-02-21 13:45:57 -0500, Doug Schwarz <see@xxxxxxxxxxxxxxxxxxx> said:
In article <47bdba3b$0$293$b45e6eb0@xxxxxxxxxxxxxxxxxxxxxxxxx>,
Arthur G <gorramfreak+news@xxxxxxxxx> wrote:
I have a general question about how best to perform operations across
multiple dimensions of multi-dimensional arrays. But let me start with
the specific example of summing across "slabs" of a 3D array.
If I want to find the "row-wise" sums, I can think of two possiblities:
sum1a = sum(sum(x, 2), 3); % Sum across columns, then slabs
sum1b = sum(x(:,:), 2); % Convert to 2D and then sum
I like the second way because I only have to use sum once, but it only
works because I am maintaining the first dimensions and "collapsing"
dimensions 2 and 3 into one.
So if I want to find the "column-wise" sum, I can still use option 1:
sum2a = sum(sum(x, 1), 3); % Sum across rows, then slabs
But approach 2 requires permuting before reshaping:
xTemp = permute(x, [2 1 3]);
sum2b = sum(xTemp(:,:));
Does anyone know of a nicer way to perform operations like sum, max,
etc. across *multiple* dimensions, that doesn't require permuting or
reshaping? Applying the operation multiple times ("Approach 1" above)
also doesn't work for me, because it requires a fixed number of
dimensions, and I'm working with anywhere from 3D to 6D arrays.
--Arthur
We can't use permute or reshape and you don't want to use sum multiple
times. You've pretty much eliminated every approach I can think of to
solve your problem.
Forgetting about your restrictions, I would use a loop. Say you want to
sum across dimensions, dims = [2 3], you could use
function y = sum_mutidim(x,dims)
y = x;
for i = 1:length(dims)
y = sum(y,dims(i));
end
Untested, but should work.
Thanks. Your solution is nice. In fact, it's pretty much exactly what I was converging on: it is very similiar to the "normal" sum, but with a little more generalization.
Also, I don't *mind* the summing multiple times, since that's probably more efficient than permute/reshape. But I still wonder if there's a more efficient way that doesn't generate intermediate arrays. I doubt it would be as readable though, so I will probably stick with your solution unless I run into speed/memory problems.
Thanks again,
Arthur
.
- References:
- Operating on multi-dimensional arrays
- From: Arthur G
- Re: Operating on multi-dimensional arrays
- From: Doug Schwarz
- Operating on multi-dimensional arrays
- Prev by Date: Re: Operating on multi-dimensional arrays
- Next by Date: Re: Deleting equivalent columns
- Previous by thread: Re: Operating on multi-dimensional arrays
- Next by thread: Re: Operating on multi-dimensional arrays
- Index(es):
Relevant Pages
|