Efficient way to sum the components of a matrix
Mostrar comentarios más antiguos
I have an array of unknown dimensions. I want to sum the values of this array. I need to do this many times. My current code is:
% Determine the number of dimensions in the array.
m = ndims(x);
% Assign the value of the array to a temporary working array, 'temp'.
temp = x;
% Calculate the total of the working array, 'temp'.
for i = 1:m
temp = sum(temp);
end
I have to do this many many times, and profile viewer is showing the command 'sum' as taking a large portion of time. Is there a more efficient way of doing this, or am I just stuck with this method?
5 comentarios
José-Luis
el 24 de Jun. de 2014
I don't understand. Are you trying to add values along a particular dimension? With the code you show, you are just calculating the same thing m times.
Adam
el 24 de Jun. de 2014
You can call sum with the dimension along which you wish to sum as its second argument, but as José-Luis says, what you are doing at the moment is unclear.
e.g.
sum( temp, 2 )
to sum along the 2nd dimension
Joseph Cheng
el 24 de Jun. de 2014
Editada: Joseph Cheng
el 24 de Jun. de 2014
Actually i thought that too jose-luis. However it appears that matlab will do the sum in one dimension each time the sum is called. perhaps it's how they choose to perform sums on single dimensions, (ie the path that chooses to do sum(1x5) and sum(5x1) arrays.)
José-Luis
el 24 de Jun. de 2014
By default, it will perform the sum along the first non-singleton dimension.
Joshua
el 24 de Jun. de 2014
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Data Type Identification en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!