how to fill gaps of rows with 3s of a matrix under certain conditions.
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
M.S. Khan
le 30 Juil 2019
Commenté : Andrei Bobrov
le 1 Août 2019
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.
0 commentaires
Réponse acceptée
Andrei Bobrov
le 30 Juil 2019
Modifié(e) : Andrei Bobrov
le 1 Août 2019
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 commentaires
Guillaume
le 1 Août 2019
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!).
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!