Calculate the sum of all the relations between a matrix components

조회 수: 1 (최근 30일)
MarshallSc
MarshallSc 2021년 6월 26일
댓글: MarshallSc 2021년 7월 8일
Hi, does anyone know how I can calculate the sum of all the relations between a matrix components? For example by having a 3*3 matrix like:
a=[a11,a12,a13;a21,a22,a23;a31,a32,a33];
I want to calculate a relation between all the components such that:
r11=((a11-a12)/(a11+a12) + (a11-a13)/(a11+a13) + (a11-a21)/(a11+a12) + (a11-a22)/(a11+a22) + (a11-a23)/(a11+a23)+...
(a11-a31)/(a11+a31) + (a11-a32)/(a11+a32) + (a11-a33)/(a11+a33))/n;
n=8; %Number of matrix components-1 in this case
I want to do this for every components of the matrix (each component has interaction with every other components) so that I have:
r12,r13,r21,r22,r23,r31,r32,r33
I used for loop but it takes a long time and long code to calculate the results (my real matrix is 101*101). Is there any simple way to do that? Thank you.
  댓글 수: 1
John D'Errico
John D'Errico 2021년 6월 26일
I don't see why a well written loop would take that long of a time here. Perhaps your problem is poorly written code? For example, are you naming individual variables r11, r12, etc?

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

채택된 답변

DGM
DGM 2021년 6월 27일
This could be done various ways. You could do this with loops if it's easier to understand. I'll just do this:
% example inputs
A = [1 2 3; 4 5 6; 7 8 9];
n = numel(A)-1;
F = @(x) sum((x-A)./(x+A),'all')/n; % define a function to calculate each sum
R = arrayfun(F,A) % calculate all of them
R = 3×3
-0.6428 -0.3651 -0.1726 -0.0282 0.0853 0.1773 0.2538 0.3184 0.3738
Using numbered variable names is a great way to cause problems for yourself. If you can embed indexing information within the variable name, then you can just use an array and index into it like normal.
  댓글 수: 3
DGM
DGM 2021년 7월 8일
I'm just going to use a loop.
A = [1 2 3; 4 5 6; 7 8 9];
B = [1 2 3; 4 5 6; 7 8 9]*10;
C = [1 2 3; 4 5 6; 7 8 9]*100;
% if you use a cell array, the relative matrix sizes don't matter
D = {A,B,C};
R = cell(size(D));
for d = 1:numel(D)
thismat = D{d};
n = numel(thismat)-1;
F = @(x) sum((x-thismat)./(x+thismat),'all')/n;
R{d} = arrayfun(F,thismat);
end
celldisp(R)
R{1} = -0.6428 -0.3651 -0.1726 -0.0282 0.0853 0.1773 0.2538 0.3184 0.3738 R{2} = -0.6428 -0.3651 -0.1726 -0.0282 0.0853 0.1773 0.2538 0.3184 0.3738 R{3} = -0.6428 -0.3651 -0.1726 -0.0282 0.0853 0.1773 0.2538 0.3184 0.3738
Of course, these example results are identical because the inputs are all proportional.
MarshallSc
MarshallSc 2021년 7월 8일
Thanks a lot DGM, really appreciate your help.

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

추가 답변 (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