필터 지우기
필터 지우기

How to create a summation looping through one matrix while keeping another one constant?

조회 수: 19 (최근 30일)
PubGamer
PubGamer 2024년 7월 7일 21:49
답변: Voss 2024년 7월 7일 22:05
Hi,
I have a function "Func" that takes 2 inputs, 1 from each a different matrix (A and B). The matrices have same number of rows, but different number of columns.
My output matrix, C, takes the summation of Func's output. For the entire row of matrix B, we will keep A constant. We will only go onto the next value of A when the B row is done. Additionally, we keep the rows the same such that only row 1 matrix B values will be used with row 1 A values. Row 2 matrix B with row 2 matrix A. etc. Here's the demo code showing what I need it to do:
A = [1, 2, 3, 4;
5, 6, 7, 8;
9, 10, 11, 12];
B = [13, 14;
15, 16;
17, 18];
% Notes:
% Input A is a 3x4 matrix
% Input B is a 3x2 matrix
% Output C is going to be same dimensions as A, 3x4
% Function "Func" takes in inputs from A and B. syntax =
% Func(input from A, input from B)
% Example of how this is supposed to look:
% C(1,1) = Func(1,13) + Func(1,14)
% Above meaning the 1,1 entry of C matrix is the summation of the output of function "Func" where the inputs is A(1,1) and B(1,1) and B(1,2)
% C(1,2) = Func(2,13) + Func(2,14)
% C(1,3) = Func(3,13) + Func(3,14)
....
% C(2,1) = Func(5,15) + Func(5,16)
% Now that we are in the 2nd row, the "Func" function uses inputs A(2,1) and B(2,1) and B(2,2)
% C(2,2) = Func(6,15) + Func(6,16)
....
% C(3,1) = Func(9,17) + Func(9,18)
....
% C(3,4) = Func(12,17) + Func(12,18)
I know how to do this brute force, but I am struggling with how to approach this problem:
  • How many for loops do I need? (I currently have 2)
  • How do I get the loop to calculate the summation? Right now, my loop is only calculating the instaneous value, not summing.
Thanks!

답변 (1개)

Voss
Voss 2024년 7월 7일 22:05
[nr,nca] = size(A);
ncb = size(B,2);
C = zeros(nr,nca);
for r = 1:nr
for ca = 1:nca
for cb = 1:ncb
C(r,ca) = C(r,ca) + Func(A(r,ca),B(r,cb));
end
end
end

태그

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by