how to subtract specific elements in matrix

조회 수: 5 (최근 30일)
wen
wen 2015년 9월 8일
댓글: wen 2015년 9월 8일
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!

채택된 답변

Guillaume
Guillaume 2015년 9월 8일
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)

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by