how to subtract specific elements in matrix
5 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
wen
el 8 de Sept. de 2015
Comentada: wen
el 8 de Sept. de 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 comentarios
Respuesta aceptada
Guillaume
el 8 de Sept. de 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)
Más respuestas (0)
Ver también
Categorías
Más información sobre Logical 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!