How to extract row data by searching in matrix.
4 views (last 30 days)
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.
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