Find number and location in matrix, make a new matrix with findings.
2 views (last 30 days)
Show older comments
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 Comments
Answers (3)
dpb
on 7 Dec 2013
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 Comments
Håvard
on 7 Dec 2013
1 Comment
dpb
on 7 Dec 2013
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
on 7 Dec 2013
Why not try normalized cross correlation, if you have the Image Processing Toolbox. Attached below is a demo.
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements 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!