필터 지우기
필터 지우기

how to fill gaps of rows with 3s of a matrix under certain conditions.

조회 수: 1 (최근 30일)
I have a matrix M.
M =
0 0 3
3 0 0
0 3 0
0 0 0
3 0 3
0 3 0
3 0 0
0 0 0
0 3 3
lets take first column, in the 2nd row is first 3 and next occurence of 3 is in the 4th row. so all should be filled with 3s inside 2nd and 4th row.
it will be like this:
3
3
3
3
then in the same first column, occurence of next 3 should be watached. its 6th row and 8th row.
if there is one zeros among 3's according to rows, it should be filled with 3. if more than one zeros among 3s with respect to rows, that rows of zeros should be filled or replaced with 4.
if its like: 3 % there is only one zeros among rows of 3s
0
3
so it should look like:
3
3
3
i want first column like this:
0
3
3
3
3
3
3
0
0
in 2nd column, first occurence of 3 is in 3rd row and next occurence of 3 is on 6th row.
it will be like this:
3
3
3
3
in the same 2nd column, next occurence of 3 is on 6th rows and next one is 9th rows.
so in next occurence, if 0s (zeros ) between 3's are more than one. it should be filled with 4.
2nd column should look like this:
0
0
3
3
3
3
4
4
3
your cooperation is highely appreciated.

채택된 답변

Andrei Bobrov
Andrei Bobrov 2019년 7월 30일
편집: Andrei Bobrov 2019년 8월 1일
Let
M = [0 0 3
3 0 0
0 3 0
0 0 0
3 0 3
0 3 0
3 0 0
0 0 0
2 3 3
0 0 0
3 0 0
0 1 0
0 0 0
3 3 3
0 0 0];
[r,c] = size(M);
m = M;
m(m == 0) = nan;
%lo - define the indices of the values that need to be changed:
lo = fillmissing(m,'previous') == 3 & fillmissing(m,'next') == 3 & isnan(m);
% ii - assign numbers to intervals, own numbering for each column:
ii = cumsum([zeros(1,c);diff(lo)>0]).*lo;
[~,jj] = ndgrid(1:r,1:c);
%{
p - count the amount of each value of matrix ii for each column
1 line the number of zeros (0's)
2 line the number of values in the first interval.
3 line the number of values in the second interval, etc.:
%}
p = accumarray([ii(:)+1,jj(:)],1);
% discard information about zeros:
p = p(2:end,:);
% a - enter the values by which our intervals will be filled (first - 3, next 4):
a = repmat([3;4*ones(max(ii(:))-1,1)],1,c);
% condition for intervals with a single value:
a(2:end,:) = a(2:end,:) - (p(2:end,:) == 1);
% replace the values in the M matrix with the values from a:
M(lo) = repelem(a(:),p(:));
  댓글 수: 9
Guillaume
Guillaume 2019년 8월 1일
See also: https://uk.mathworks.com/matlabcentral/answers/474418 where the OP asked the same question (and is equally unclear as to the criteria for 3 or 4, which apparently can also be 5, 6 or anything else!).

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by