Find a number inside a matrix

40 views (last 30 days)
jean claude
jean claude on 28 Oct 2020
Edited: Jon on 30 Oct 2020
  2 Comments
Walter Roberson
Walter Roberson on 28 Oct 2020
This does not appear to be a MATLAB question.
jean claude
jean claude on 28 Oct 2020
exactly you're right ! basically it's a python question since i am not that good in python i tried to solve it by matlab first after that convert to python, what do you think ?

Sign in to comment.

Answers (1)

Jon
Jon on 28 Oct 2020
There are probably more efficient ways to do this but one approach would be to utilize MATLAB's find function.
If your matrix were given by A you can find for example the locations of all of the 8's using
[mIdx,nIdx] = find(A == 8)
Note this returns a vector, mIdx of row indices and vector nIdx of column indices where the 8's are located.
You could then find all of the 2's using
[pIdx, qIdx] = find( A == 2)
you could then check for each pair indices whether they were adjacent (within 1 element of each other)
if so add it to the list and so on
  2 Comments
jean claude
jean claude on 30 Oct 2020
can you develop please! 3 days in my room and i cannot resolve this!!
Jon
Jon on 30 Oct 2020
Edited: Jon on 30 Oct 2020
3 days in your room is too long :)
I think one approach would be to think of this as a recursive graph traversal where you are trying to find the whole sequence. Your search starts on one of the 8's. You look 1 column to the left. Is it a 2? If it it is then move to that 2, if not then look 1 row above etc until you either find an adjacent 2 or you eliminate that 8 as being isolated. Once you move to the 2 then you similarly look for adjacent 9's. If you find one then move to that 9 add it to the list of traversed nodes so far and start looking for an adjacent 2. When you hit a dead end back up. Continue in this manner until you either reach your final digit or have hit a dead end. I would suggest first doing it by hand (with a pencil and a sheet of paper) working through how you do it. Then see if you can implement it. I'm thinking you'd use the find command just to find all of the 8's which would be the starting points for your search. Then you'd dive into each one with your recursive search. In your recursive function you will need to keep track of the digits you've found so far and the last location you came from so you can go back. You also need a condition that sends you back up, either you've hit a dead end or you've found your final digit. If you aren't familiar with doing these kind of graph searches look for example at how people do depth first search of a graph to get some ideas.

Sign in to comment.

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!