フィルターのクリア

Replacing a zero value of a matrix with the value left to it

1 回表示 (過去 30 日間)
Wietze Zijpp
Wietze Zijpp 2022 年 4 月 6 日
編集済み: DGM 2022 年 4 月 6 日
Suppose I have a matrix
A =
8 1 6
3 0 7
4 9 2
Now I would like the 0 value to be replaced by the value 3 (the value left of it).
This is an illustrative example for a small matrix. I would like to apply this approach to a much larger matrix
  2 件のコメント
Torsten
Torsten 2022 年 4 月 6 日
What if there is another 0 left to it ? Or if the 0 is in the first column ?
Wietze Zijpp
Wietze Zijpp 2022 年 4 月 6 日
Good Question, One way to deal with this could be to search for a value which is not and then replace the zeros with that value

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

採用された回答

Star Strider
Star Strider 2022 年 4 月 6 日
One approach using fillmissing
A = [8 1 6
3 0 7
4 9 2];
A(A==0) = NaN;
B = fillmissing(A,'previous',2) % With Original Matrix
B = 3×3
8 1 6 3 3 7 4 9 2
A = [8 1 6
0 0 7
4 9 2];
A(A==0) = NaN;
B = fillmissing(A,'nearest',2) % With Matrix With First Two Rows Being Zero
B = 3×3
8 1 6 7 7 7 4 9 2
It would be necessary to use an if block to test for the second condition and then choose the 'nearest' method for that condition. That could go something like this:
A = [8 1 6
0 0 7
4 9 2
5 0 0];
B = A; % Create Result MAtrix
B(B==0) = NaN;
for k = 1:size(A,1)
ixr = find(A(k,:)==0);
if ~isempty(ixr) & any(ixr==1)
B(k,:) = fillmissing(B(k,:),'nearest',2);
elseif ~isempty(ixr) & ~any(ixr==1)
B(k,:) = fillmissing(B(k,:),'previous',2);
end
end
A
A = 4×3
8 1 6 0 0 7 4 9 2 5 0 0
B
B = 4×3
8 1 6 7 7 7 4 9 2 5 5 5
The loop, and testing each row, seems to me to be the only way to code this, considering that two different interpolation methods are required, depending on the position of the zeros in each row.
.
  1 件のコメント
DGM
DGM 2022 年 4 月 6 日
編集済み: DGM 2022 年 4 月 6 日
Well this is way neater than what I came up with, but I can offer this bit of a modification from what I was doing:
A = [8 1 6
0 3 7 % this row uses 'nearest'
4 9 2
5 0 0];
B = [fliplr(A) A]; % book-matched array
B(B==0) = NaN;
B = fillmissing(B,'previous',2);
B = B(:,size(A,2)+1:end) % trim off excess
B = 4×3
8 1 6 3 3 7 4 9 2 5 5 5

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

その他の回答 (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