how to subtract specific elements in matrix

2 Ansichten (letzte 30 Tage)
wen am 8 Sep. 2015
Kommentiert: wen am 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!
0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Guillaume am 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)
1 Kommentar-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden
wen am 8 Sep. 2015
thx a lot!

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by