Summation of column elements of matrix A from index values of matrix B

6 visualizaciones (últimos 30 días)
Suppose I have matrix A=3x3 and B=3x3. I sort each column of B and get index matrix I by using [C,I]=sort(B). Now I will take first column Indices of matrix I and want to sum the corresponding elements of column A pertaining to these indices. Now I will take second column index of matrix I and sum the corresponding elements of A and so on till 4th element. I want to store these 4 sum values.
E.g. A=[1 2 3;2 3 4; 4 5 6] , B=[10 13 2; 23 24 3; 21 19 21]
Now [C,I] =sort (B), then I= [1 1 1 ;3 3 2;2 2 3]. The first column of I is [1 3 2]. Now I want to sum elements of A i.e. 1st element from first column, 3rd element from 2nd column and 2nd element from 3rd column ( 1+5+4). Store this value. Then I take 2nd column of I i.e. [1 3 2]. Again repeat summation of A as stated for 1st column (1+5+4). Then I take 3rd column of I and repeat step for A for summation (1+3+6). Now I want to store these 3 summation values in D( i.e. 10 10 10).
Pls suggest code.

Respuesta aceptada

Matt J
Matt J el 8 de Jun. de 2022
Editada: Matt J el 8 de Jun. de 2022
A=randi(10,3) , B=randi(10,3);
A = 3×3
9 9 6 10 6 9 1 2 6
[m,n]=size(B);
[~,I]=sort(B),
I = 3×3
3 2 2 1 1 3 2 3 1
J=repmat((1:n)',1,m);
D=sum( A( sub2ind(size(A),I,J) ) )
D = 1×3
19 25 18

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by