How to extract row data by searching in matrix.

5 views (last 30 days)
Hello there!
I am coding a Monte Carlo model, but right now I don't know you to achive the next:
I have the matrix Species = zeros(1,7); the size of the matrix for the rows depends on the number of iterations and particles in the system.
Here I use the Species matrix to save data about the particles,
Species = [ #atom, type of event, coordinate X, coordinate Y, time, general time, special events]
I am looking for a efficent method to extract data from this matrix by searching via coordinates, for example I have x=45 and y=105. I want to find the row where x=45 and y=105 are located and extract all the data from that row.
Thanks
  2 Comments
Kevin Holly
Kevin Holly on 3 Oct 2022
Edited: Kevin Holly on 3 Oct 2022
Species = [round(125*rand(3000,2)),(1:3000)']
Species = 3000×3
85 41 1 27 79 2 9 1 3 94 74 4 67 91 5 97 111 6 81 12 7 0 56 8 68 107 9 20 3 10
Species(Species(:,1)==45 & Species(:,2)==105,:)
ans = 1×3
45 105 2992
Hussien Ali
Hussien Ali on 4 Oct 2022
Edited: Hussien Ali on 4 Oct 2022
Thank you very much. I was trying via "find" but the process was very slow.

Sign in to comment.

Answers (1)

dpb
dpb on 3 Oct 2022
x=45; y=105; % lookup values; use variables, don't bury magic numbers in executable code
ixy=(Species(:,3)==x)&(Species(:,4)==y); % the brute force addressing vector in array form
SpeciesXY=Species(ixy,:); % the desired subset of the original
Of course, one doesn't have to actually create another array; one can use the results dynamically however needed as argument to functions, etc., ... however, doing this over and over and over ... gets old after a while, so passing the array to a function is one way to generalize the code.
A way you could consider depending upon how you're going to use the data and the processing to be done would be to put the return variables into a table instead of just a dumb ol' array --
Species=table(atom,event,X,Y,time,general time,special events);
ixy=(Species.X==x)&(Species.Y==y); % the table variables way with identifiable variable names way
And, with the above, look carefully into rowfun and the general section on splitapply and grouping variables. It's sometimes amazing how little code it takes to process a comples dataset.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!