필터 지우기
필터 지우기

Efficient way to sum the components of a matrix

조회 수: 1 (최근 30일)
Joshua
Joshua 2014년 6월 24일
댓글: Joshua 2014년 6월 24일
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
José-Luis
José-Luis 2014년 6월 24일
By default, it will perform the sum along the first non-singleton dimension.
Joshua
Joshua 2014년 6월 24일
Sorry, I didn't make it very clear. I have an array of unknown dimension and I want to sum up all of the values within that array.
x = [ 0 1 ; 2 3]
code to sum all of the values across all dimensions...
temp = 6

댓글을 달려면 로그인하십시오.

채택된 답변

Joseph Cheng
Joseph Cheng 2014년 6월 24일
if you are just looking for the total sum of the n dimensional array, then you can just do sum(temp(:));

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by