Effacer les filtres
Effacer les filtres

how to subtract specific elements in matrix

2 vues (au cours des 30 derniers jours)
wen
wen le 8 Sep 2015
Commenté : wen le 8 Sep 2015
Hi, suggest we have two matrix
and I want the difference between two elements as long as they have different indices. For example, in the first row, two elements (12.85... and 10) have the same indices(1,10), so we don't calculate the difference. But in the row, 13.46... (2,8) and 10(2,10) have different indices, so we need to calculate the difference between them, which is 3.46... Finally, I want to sum all these difference.
Many thanks!

Réponse acceptée

Guillaume
Guillaume le 8 Sep 2015
Assumption: There's always one and only one non-zero element in each matrix, and the matrices have the same size
assert(all(sum(ob ~= 0, 2) == 1) && all(sum(tb ~= 0, 2) == 1)) %check 1st assumption
assert(isequal(size(ob), size(tb))) %check 2nd assumption
Step 1: find the indices of non-zero column in each row using find. Because find works column-wise, transpose the matrices and the problem becomes: find non-zero row in each column:
[obcol, ~] = find(ob'); %the ~ is required as you want the two return value version of find
[tbcol, ~] = find(tb');
Step 2: compare the indices and when they differ extract the corresponding element from each matrix using sub2ind:
differcol = obcol ~= tbcol;
rowindices = (1:size(ob, 1))';
rowindices = rowindices(differcol); %indices of row where non-zero column differ
obvalues = ob(sub2ind(size(ob), rowindices, obcol(differcol)));
tbvalues = tb(sub2ind(size(tb), rowindices, tbcol(differcol)));
Step 3: subtract the differences and sum it all:
diffsum = sum(obvalues - tbvalues)

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by