Find number and location in matrix, make a new matrix with findings.
2 次查看(过去 30 天)
显示 更早的评论
I am trying to make a function which is to find a certain number, or numbers above a threshold number, in a given matrix of unknown size. Preferably without any other function then if,else,while,for.
function search = searchMatrix(matrix)
search = [];
[r c] = size(matrix);
for i = 1:r
for j = 1:c
if (matrix(i,j) >= 2000)
search = matrix(i,j) && i && j;
end
end
end
But I would like the numbers, and the location of the numbers to be put into a new matrix "search" with each new row corresponding to these numbers and location.
E.g:
[ 2300 4 5 ; 4320 8 2 ; 2001 9 4]
Im not sure how to proceed for doing so. Any suggestions?
0 个评论
回答(3 个)
dpb
2013-12-7
Preallocate search for speed improvement in large cases, then populate the array. To cover the worst-case, it would have to be numel(matrix) in size...
srch=zeros(numel(m),1); % preallocate
Then
srch(i,:)=[m(i,j i j]; % each found element
If you keep an additional counter you can truncate unused rows using it to avoid the use of another builtin ( any, all, etc.) or another logical test.
0 个评论
Håvard
2013-12-7
1 个评论
dpb
2013-12-7
A) The handling of the values is owing to not incrementing another counter for the location...
n=0;
...
if m(i,j)>setpoint,
n=n+1;
s(n,:)=[m(i,j) i j];
...
B) As for truncation, as suggested earlier, you have to truncate to the used portion. Now having n, when done thru the loop
s(n+1:end,:)=[]; % clear unused rows
And, of course, while I presume these exercises are pedagogical self-teaching tools, "the Matlab way" would be to use logical addressing and eliminate the loops entirely.
Image Analyst
2013-12-7
Why not try normalized cross correlation, if you have the Image Processing Toolbox. Attached below is a demo.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!