フィルターのクリア

If only one positive elem per row (rest are 0), then fill both sides of positive element

1 回表示 (過去 30 日間)
Hi, I have a square matrix of non-negative elements. In each row, at least one element is positive.
For rows where there is only one positive element (the rest are 0) I need to put 1e-4 next to that element, both sides. In A below, the second and last row have only 1 positive (note last row has only one side to add)
A=...
[0.9 0.1 0 0;
0 0.8 0 0;
0 0.1 0.7 0.1;
0 0 0 0.9]
Ouput should be:
B=...
[0.9 0.1 0 0;
1E-4 0.8 1E-4 0;
0 0.1 0.7 0.1;
0 0 1E-4 0.9]
The dimension of the matrix is fixed, so I can get rows that need to be changed (if result is 3 in this case) with
sum(A==0,2)
But this doesn't tell me the position of the positive element (I could use something like find(A) ) , nor fill both sides (loop free if possible)

採用された回答

Guillaume
Guillaume 2015 年 2 月 20 日
A = [0.9 0.1 0 0
0 0.8 0 0
0 0.1 0.7 0.1
0 0 0 0.9];
Apadded = [zeros(size(A, 1), 1) A zeros(size(A, 1), 1)]; %pad to avoid dealing with edges
lonelyrows = find(sum(A ~= 0, 2) == 1);
[~, singlecols] = find(Apadded(lonelyrows, :));
Apadded(sub2ind(size(Apadded), [lonelyrows lonelyrows], [singlecols-1 singlecols+1])) = 1e-4;
Afilled = Apadded(:, 2:end-1)

その他の回答 (2 件)

Sean de Wolski
Sean de Wolski 2015 年 2 月 20 日
編集済み: Sean de Wolski 2015 年 2 月 20 日
And just for fun:
A=...
[0.9 0.1 0 0;
0 0.8 0 0;
0 0.1 0.7 0.1;
0 0 0 0.9];
B = A;
sgn = sign(A)==1;
B(logical(conv2(double(bsxfun(@and,sum(sgn,2)==1,sgn)),[1 0 1],'same'))) = 1e-4

dpb
dpb 2015 年 2 月 20 日
Find the locations needing to be worked around. Pick one dimension first as you've done; I'll stick with the rows...
>> irow=find(sum(A>0,2)==1)
irow =
2
4
>> [~,icol]=ind2sub(size(A(irow,:)),find(A(irow,:)>0))
icol =
2
4
>>
These are now indices in the original array since didn't reduce the number of columns by subselecting the rows.
  2 件のコメント
Dave
Dave 2015 年 2 月 20 日
Thanks dpb, those are the locations, how do I fill next to them with 1E-4?
dpb
dpb 2015 年 2 月 20 日
Ran out of time...methinks bsxfun the irow,icol array of indices with padded array as Guillame did would also work...

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

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by