# Allocating first and last rows from column 2 that correspond to specific criteria in column 1 in a for loop to a new matrix or submatrix

1 Ansicht (letzte 30 Tage)
Lina Koronfel am 13 Jul. 2020
Kommentiert: Lina Koronfel am 13 Jul. 2020
I have a binary matrix consisting of 10100 x 15 elements where elements==1 are grouped in n sequential rows per column and their index differs in each column. For example
X =
1 0 0 0
1 1 1 0
1 1 1 1
0 1 1 1
0 0 0 1
What I aim to do, is to replace the 10100 rows per each column with the the first and last indeces of value==1. Thus in each column I should only have 2 rows representing the indeces of interest.The final output should be a matrix that looks something like that:
Index_X=
1 2 2 3
3 4 4 5
Please let me know if there is a neat way to obtain the indeces of rows/col of the main matrix X. This is the code I'm currently using and it is not giving me what I want:
for j=1:15; %15 is the total number of columns in the original matrix
%....code to obtain X matrix 10100x15
[row col]=find(ismember(X,1));
concatenate_colrow=cat(2,col,row); % this yields indeces of columns ==1 in original matrrix in (:,1) and indeces or adjacent rows in (:,2)
%.....should I do something here to obtain the rows indeces==1 and placing as in example above?????
end
Thank you
##### 0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Akzeptierte Antwort

Stephen23 am 13 Jul. 2020
Bearbeitet: Stephen23 am 13 Jul. 2020
X = [1,0,0,0;1,1,1,0;1,1,1,1;0,1,1,1;0,0,0,1];
N = size(X,2);
Y = nan(2,N);
for k = 1:N
V = find(X(:,k));
Y(:,k) = V([1,end]);
end
giving
Y =
1 2 2 3
3 4 4 5
##### 4 Kommentare2 ältere Kommentare anzeigen2 ältere Kommentare ausblenden
Lina Koronfel am 13 Jul. 2020
Oh sorry that was a typo while copying. However, I realized what the issue is. The first 2/15 columns are lacking value==1. Thus the find function yielded an empty array that could't be processed by the following line Ywhatever(:,k)=LED_rowcol_index([1,end]);.
I changed the for loop to start from 3 instead of 1 and now it is working.
for k =3:BinarySize
LED_rowcol_index=find(X:,k));
Ywhatever(:,k)=LED_rowcol_index([1,end]);
end
Lina Koronfel am 13 Jul. 2020

Melden Sie sich an, um zu kommentieren.

### Kategorien

Mehr zu Resizing and Reshaping Matrices finden Sie in Help Center und File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by