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)
  1 件のコメント
wen
wen 2015 年 9 月 8 日
thx a lot!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by