Find first and last NaN/Finite element in each row of a large array.
29 views (last 30 days)
Show older comments
Gonzalo Molina
on 15 Jun 2020
Commented: Gonzalo Molina
on 15 Jun 2020
Hello everyone,
I've modified a prexisten array to convert the non-interest values into NaN and now I want to define different regions of the new array throughout the identification of the finite elements.
As te region of interest would be always in the center of the array, each row is composed by x*NaN - y*Finite - z*NaN elements
example_row_1= [NaN NaN 1 2 3 4 NaN NaN NaN]
example_row_2= [NaN NaN NaN 1 2 NaN NaN NaN NaN]
I would like to identify the first and last finite element of each row in order to define the vector of elements comprised between both values.
I've tried something like this:
for i = 1:rows
for j = 1:columns
[regions(i,1), regions(i,2)] = find(isfinite(phases(i,:)), 1); % find the first non NaN element in the matrix
[regions(i,3), regions(i,4)] = find(isfinite(phases(i,:)), 1, 'last'); %find the last non NaN element in the row
end
end
I would like to extract the (i, j) indexes of each position.
Thank you.
Accepted Answer
Ameer Hamza
on 15 Jun 2020
Edited: Ameer Hamza
on 15 Jun 2020
Try something like this
example_row_1 = [NaN NaN 1 2 3 4 NaN NaN NaN];
example_row_2 = [NaN NaN NaN 1 2 NaN NaN NaN NaN];
M = [example_row_1; example_row_2];
[r, c] = find(~isnan(M));
idx = accumarray(r, c, [], @(x) {[min(x) max(x)]});
idx = vertcat(idx{:});
Result
>> idx
idx =
3 6
4 5
The first column of idx shows the index of the first non-NaN element in that row, 2nd column shows index last non-Value value.
3 Comments
Ameer Hamza
on 15 Jun 2020
The idx, in my answer, is not an absolute index. It is the row-wise index. [3 6] is the non-NaN region of the first row. [4 5] is the non-NaN region of the second row. I think you want something like the following
example_row_1 = [NaN NaN 1 2 3 4 NaN NaN NaN];
example_row_2 = [NaN NaN NaN 1 2 NaN NaN NaN NaN];
M = [example_row_1; example_row_2];
[r, c] = find(~isnan(M));
idx = zeros(size(M, 1), 4);
vals = accumarray(r, c, [], @(x) {[min(x) max(x)]});
idx(:,[2 4]) = vertcat(vals{:});
idx(:,[1 3]) = [1:size(M,1); 1:size(M,1)].';
Result
>> idx
idx =
1 3 1 6
2 4 2 5
More Answers (1)
madhan ravi
on 15 Jun 2020
First = find(~isnan(row1), 1, 'first’)
Last = find(~isnan(row1), 1, 'last')
0 Comments
See Also
Categories
Find more on Resizing and Reshaping Matrices 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!