# How to average first two dimension of 3D array/matrix?

조회 수: 21(최근 30일)
UTKARSH VERMA 2021년 9월 1일
댓글: UTKARSH VERMA 2021년 9월 1일
Hi all,
I am calculating the average of first two dimension of a 3D matrix but it is showing following error:
Error using sum
Dimension argument must be a positive integer scalar within indexing range.
Error in mean (line 116)
y = sum(x, dim, flag) ./ size(x,dim);
Also, I have used a simplest example given in topic 'Mean of Array Page' in https://in.mathworks.com/help/matlab/ref/mean.html but I am getting same error.
I am using MATLAB 2018a
##### 댓글 수: 2표시 이전 댓글 수: 1숨기기 이전 댓글 수: 1
UTKARSH VERMA 2021년 9월 1일
I have used a simplest example given in topic 'Mean of Array Page' in https://in.mathworks.com/help/matlab/ref/mean.html and I got an error:-
""Error using sum
Dimension argument must be a positive integer scalar within indexing range.
Error in mean (line 116)
y = sum(x, dim, flag) ./ size(x,dim);""
I guess my Matlab version is older (i.e. 2018a)

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

### 채택된 답변

Chunru 2021년 9월 1일
편집: Chunru 2021년 9월 1일
a = randi(3, 3, 4, 2)
a =
a(:,:,1) = 3 3 1 3 3 1 2 3 3 1 3 1 a(:,:,2) = 3 1 1 2 1 1 2 2 1 3 1 1
c = mean(reshape(a, [], size(a,3)))
c = 1×2
2.2500 1.5833
##### 댓글 수: 1표시 없음숨기기 없음
UTKARSH VERMA 2021년 9월 1일
Thank you Chunru!
It worked perfectly.

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

### 추가 답변(2개)

Wan Ji 2021년 9월 1일
편집: Wan Ji 2021년 9월 1일
Just use mean function to average first two dimension of 3D matrix
a = rand(2,3,4); % I just use rand function so the result is randomly displayed
b = mean(a,1:2) % 1:2 means the first two dimension
The result is
b = mean(a,1:2)
b(:,:,1) =
0.5258
b(:,:,2) =
0.2759
b(:,:,3) =
0.6214
b(:,:,4) =
0.4449
If you want to get array of b
Then
b = squeeze(b) % or b = b(:);
So
b =
0.5258
0.2759
0.6214
0.4449
##### 댓글 수: 1표시 없음숨기기 없음
UTKARSH VERMA 2021년 9월 1일
I guess my Matlab version is older (i.e. 2018a) due to which I am not able to get my result and it's showing same problem.

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

Steven Lord 2021년 9월 1일
The ability to specify a vector of dimensions over which to sum an array was introduced in release R2018b as stated in the Release Notes.
##### 댓글 수: 1표시 없음숨기기 없음
UTKARSH VERMA 2021년 9월 1일
Thanks for sharing this information. I didn't know that.

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

### 범주

Find more on Operators and Elementary Operations in Help Center and File Exchange

R2018a

### Community Treasure Hunt

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

Start Hunting!