How to extract row data by searching in matrix.
5 次查看(过去 30 天)
显示 更早的评论
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 个评论
Kevin Holly
2022-10-3
编辑:Kevin Holly
2022-10-3
Species = [round(125*rand(3000,2)),(1:3000)']
Species(Species(:,1)==45 & Species(:,2)==105,:)
回答(1 个)
dpb
2022-10-3
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!