Calculate the sum of all the relations between a matrix components

2 visualizaciones (últimos 30 días)
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:
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:
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 comentario
John D'Errico
John D'Errico el 26 de Jun. de 2021
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?

Iniciar sesión para comentar.

Respuesta aceptada

DGM el 27 de Jun. de 2021
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 comentarios
MarshallSc el 8 de Jul. de 2021
Thanks a lot DGM, really appreciate your help.

Iniciar sesión para comentar.

Más respuestas (0)


Más información sobre Loops and Conditional Statements en Help Center y File Exchange.


Community Treasure Hunt

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

Start Hunting!

Translated by