Find the first and last 1 in each column
Show older comments
I have a matrix like this
X = [NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 0 0 0 0 NaN NaN NaN NaN NaN
0 0 0 0 0 NaN NaN NaN NaN NaN
NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN];
I need to find the index of row for the first and last 1 in each column taking in account there are NaNs and some columns don't have any 1 and others columns have just NaNs. If the column does not have a 1, it just go to the next column, so the results of this matrix would be =[6 13 4 ].
Answers (2)
first = zeros(1, size(X, 2)); % Pre-allocation
last = first;
for k = 1:size(X, 2)
indexI = find(X(:, k) == 1, 1, 'first');
indexF = find(X(:, k) == 1, 1, 'last');
if ~isempty(indexI)
first(k) = indexI;
last(k) = indexF;
end
end
first = first(first ~= 0); % Remove all zeros
last = lasst(first ~= 0);
Another solution:
Y = X .* (1:size(X, 1)).'; % Replace 1s by the column index
Y(X == 0) = NaN; % Let all but the former 1s be NaN
first = min(Y, [], 1);
last = max(Y, [], 1);
first(isnan(first)) = []; % Remove NaNs
last(isnan(last)) = [];
X = [NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 0 0 0 0 NaN NaN NaN NaN NaN
0 0 0 0 0 NaN NaN NaN NaN NaN
NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN];
% Find first 1 per column (ignore columns without 1s)
[r,c] = find(X==1);
[~,cidx] = unique(c);
z = r(cidx)
% Find last 1 per column (ignore columns without 1s)
[r,c] = find(flipud(X)==1);
[~,cidx] = unique(c);
z = size(X,1)-r(cidx)+1
Categories
Find more on NaNs in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!