How to replace the trapped zeros by previous number in a given matrices keeping leading and trailing zeros fixed?
2 次查看(过去 30 天)
显示 更早的评论
Hi Matlab experts,
I have a matrix
A=[ 0 0 0 1 0 2 3 1 2 3 0 0 0
1 2 2 1 1 2 3 1 2 3 1 3 4
0 1 0 1 0 0 0 1 2 1 1 2 2
2 1 2 1 0 0 0 0 1 1 1 1 1
1 0 0 1 1 1 1 1 2 2 2 1 1];
And I want to replace all trapped zeros by previous number. for instance, In first column we have 1 0 2 I want to change this into 1 1 2. Similarly, In third column, I want to replace 2 0 2 by 2 2 2. In fifth column 1 0 0 1 by 1 1 1 1. In sixth column, 2 0 0 1 by 2 2 2 1 and so on for all columns. Just want to replace by all trapped zeros in each column by its preceeding non-zero digit Keeping leading and trailing zeros fixed. So that my final matrix looks something like this...
A=[ 0 0 0 1 0 2 3 1 2 3 0 0 0
1 2 2 1 1 2 3 1 2 3 1 3 4
1 1 2 1 1 2 3 1 2 1 1 2 2
2 1 2 1 1 2 3 1 1 1 1 1 1
1 0 0 1 1 1 1 1 2 2 2 1 1];
4 个评论
Voss
2022-3-23
编辑:Voss
2022-3-23
OK, let me rephrase. What if you have A as in your question, except A(4,2) is 0, like this:
A=[ 0 0 0 1 0 2 3 1 2 3 0 0 0
1 2 2 1 1 2 3 1 2 3 1 3 4
0 1 0 1 0 0 0 1 2 1 1 2 2
2 0 2 1 0 0 0 0 1 1 1 1 1
1 0 0 1 1 1 1 1 2 2 2 1 1];
% ^ I put a 0 in the 4th row (not a "trapped zero", I presume)
The method used in the Accepted Answer puts a 1 in that spot:
r=size(A,1);
c=size(A,2);
for i=2:r-1
for j=1:c
if A(i,j)==0
A(i,j)=A(i-1,j);
end
end
end
disp(A)
% ^ 4th row, 2nd column is now 1
Is that the right thing to do?
采纳的回答
Arif Hoq
2022-3-22
编辑:Arif Hoq
2022-3-22
try this:
A=[ 0 0 0 1 0 2 3 1 2 3 0 0 0
1 2 2 1 1 2 3 1 2 3 1 3 4
0 1 0 1 0 0 0 1 2 1 1 2 2
2 1 2 1 0 0 0 0 1 1 1 1 1
1 0 0 1 1 1 1 1 2 2 2 1 1];
r=size(A,1);
c=size(A,2);
for i=2:r-1
for j=1:c
if A(i,j)==0
A(i,j)=A(i-1,j);
end
end
end
disp(A)
expected_output=[ 0 0 0 1 0 2 3 1 2 3 0 0 0
1 2 2 1 1 2 3 1 2 3 1 3 4
1 1 2 1 1 2 3 1 2 1 1 2 2
2 1 2 1 1 2 3 1 1 1 1 1 1
1 0 0 1 1 1 1 1 2 2 2 1 1];
isequal(A,expected_output) % just for checking that input A and expected output is equal
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!