how to find range of elements in each row of a matrix
1 次查看(过去 30 天)
显示 更早的评论
i have a matrix of 8 x 5 and i want if there are at least two values in a row that lies between 6 and 8,then store the locations of those value else decrease the lower value from 6 to 5 and check if any value lies between 5 &8 else increase the upper value to 9 and check the values of a row lies between 7&9...I need to set the the range for each row and to store the location of the values in each row that lie in a specified range
2 个评论
Walter Roberson
2017-2-20
This sounds like "make work" for a homework assignment, rather than something that would have real use??
回答(3 个)
Image Analyst
2017-2-20
If you want the range, why do it like that unusual way, which won't necessarily find the true range? Why not simply do this:
m = 9 * rand(5, 8) % Sample data
for row = 1 : 5
[minValue(row), colOfMin(row)] = min(m(row,:));
[maxValue(row), colOfMax(row)] = max(m(row,:));
end
Walter Roberson
2017-2-20
Let M be your matrix.
nrow = size(M,1);
location_to_remember = zeros(nrow, 1);
active_rows = 1 : nrow;
for thresh = [6 5 7; 8 8 9]
mask = M(active_rows, 1:end-1) >= thresh(1) & M(active_rows, 1:end-1) <= thresh(2) & ...
M(active_rows, 2:end) >= thresh(1) & M(active_rows, 2:end) <= thresh(2);
rows_with_matches = find( any(mask,2) );
for K = 1 : rows_with_matches
this_relative_row = rows_with_matches(K);
first_matchpair_in_row = find( mask(this_relative_row, :), 1, 'first' );
this_orig_row = active_rows(this_relative_row);
location_to_remember(this_orig_row) = first_matchpair_in_row;
end
active_rows(rows_with_matches) = [];
end
It is possible to vectorize the finding of the match pair instead of using the for K loop, but the code to do so would be less than clear.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!