MATLAB Answers

Differencing Across 2 Different Sized Matrices

조회 수: 1(최근 30일)
Brian DeCicco
Brian DeCicco 2021년 7월 15일
답변: Mathieu NOE 2021년 7월 15일
MATLAB Community,
I am trying to loop through and difference across 2 differently sized matrices. Both matrices are 3-dimentional, containing the same first dimension (longitude) and second dimension (latitude) values, but differing 3rd dimension (temperature data) sizes. Matrix 1 is 1440x721x480 and Matrix 2 is 1440x721x12. Matrix 1 contains monthly averages of temperature for 40 years (i.e. Jan '79, Feb '79,...Dec '18) and Matrix 2 contains the 40 year average of temperature for each of the 12 months (i.e. all Jan, Feb, Mar,...Dec). I'd like to take all of the Jan months from Matrix 1 and subtract each by the 40-year Jan average in Matrix 2, and then move on to Feb, Mar,...Dec and do the same thing. My resulting matrix (Matrix 3) should be of size 1440x721x480 in the end. I know that I will likely have to create a double for loop, but am unsure how to get it just right. Here is my coding so far:
Matrix_3 = zeros(1440,721,480);
for i = 1:480
for j = 1:12
Matrix_3(:,:,i) = Matrix_1(:,:,(i-1)+1:12:480) - Matrix_2(:,:,j);

채택된 답변

Mathieu NOE
Mathieu NOE 2021년 7월 15일
I think this works fine with a single loop :
% dummy data
Matrix_1 = randn(1440,721,480);
Matrix_2 = randn(1440,721,12);
% init Matrix_3
Matrix_3 = zeros(1440,721,480);
for ci = 1:12
ind_mat1 = (ci:12:480);
ind_mat2 = ci;
Matrix_3(:,:,ind_mat1) = Matrix_1(:,:,ind_mat1) - Matrix_2(:,:,ind_mat2);

추가 답변(0개)

Community Treasure Hunt

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

Start Hunting!

Translated by