How to manipulate a matrix under certain conditions to fills gaps with numbers.
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
M.S. Khan
am 1 Aug. 2019
Kommentiert: M.S. Khan
am 4 Aug. 2019
M is a small matrix. i am working on Big Matrix. My focus is on central (Middle) column. Using mid column, i want to fill (repalce '0' with '3' & '4') according to their positions in the mid colums with to respect to all rows.
M = [0 3 0
0 3 0
3 0 0
0 0 0
0 3 0
3 3 3
0 0 0
0 0 0
0 0 0
0 3 0
3 3 0
0 0 0
3 0 0
0 3 0
0 3 3
0 0 0
0 0 0
0 3 0
0 0 0]
In first occurence of 3 and next occurence of 3 should be filled with 3s. carry on the same mid column, in next occurence from first to next one (6th to 10th rows)should be filled with 4s. Continue by same column, 13 th and 14th rows should be filled as 4 while next occurence of 3 and next 3s gaps( 17th to 19th rows) should be filled with 3
I want to get the 'required colum' where 0's are replaced with bold numbers 3s and 4s with respect to their positions of rows in the mid colum of Matrix M.
Your help and cooperation will be highly appreacitead. Regards in advance.
Mid column Required
3 3
3 3
0 3
0 3
3 3
3 3
0 4
0 4
0 4
0 4
3 3
3 3
0 4
0 4
3 3
3 3
0 3
0 3
0 3
3 3
0 0
7 Kommentare
Akzeptierte Antwort
Andrei Bobrov
am 1 Aug. 2019
Bearbeitet: Andrei Bobrov
am 1 Aug. 2019
Let MM - your 'required colum'.
MM =[3,3,0,0,3,3,0,0,0,3,3,0,0,3,3,0,0,3,0]';
m = MM;
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:
ii = cumsum([0;diff(lo)>0]).*lo;
%{
p - count the amount of each value of vector ii:
1 element - the number of zeros (0's);
2 element the number of values in the first interval.
3 element the number of values in the second interval, etc.:
%}
p = accumarray(ii(:)+1,1);
% Let a - the values for to be changed (vector with length equal max(ii), in our case - 4):
a = [3,4,4,3]'; % HERE fixed..
% Condition for intervals with length equal 1
a(p == 1) = 3;
% Replacement:
MM(lo) = a(ii(lo));
12 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!