Finding and counting numbers from one matrix in another
Afficher commentaires plus anciens
Hello all
I have a question, which seems complex to me but probably isn't.
I have two matrices and I am trying to find and count each number from one matrix in another.
For example: Lets say I have two matrices A and B. A is a list of nodes (mx1) and B is a list of triangles that contain those nodes (nx3).
I need to find all the nodes from A that are in B, count how many times they appear and in which triangles they appear.
So in the end I will get two new matrices, C=[nodeID, No. of times it appears in all columns in B] and D=[node ID, list of triangles (1:9) that contain that node (will contain 0s for nodes that few elements attached].
I have tried to use find and ismember but they don't see to do exactly what I want.
I hope I've explained that well enough. Help is very much appreciated.
Meghan
Réponse acceptée
Plus de réponses (1)
Another method of obtaining the result, which works regardless of the values of the node ids, and whether or not a node is present in any triangle
%A: column vector of ids
[~, id] = ismember(B(:), A);
C = [A, accumarray(nonzeros(id), 1)]; %nonzero not required if all nodes are sure to be found in triangles
trigids = repmat((1:size(B, 1))', 1, size(B, 2));
triglist = accumarray(nonzeros(id), trigid(find(id)), [], @(list) {[list.', nan(1, 9-numel(list))]}); %again nonzeros and find(id) not needed if all nodes are sure to be found
triglist(cellfun(@isempty, triglist)) = {nan(1, 9)};
D = [A, cell2mat(triglist)]
Alternatively, D could be generated with a loop:
D = [A, nan(numel(A), 9)];
for rowid = 1:numel(A)
[trigid, ~] = find(B == A(rowid));
D(rowid, 2:numel(trigid)+1) = trigid;
end
4 commentaires
dpb
le 16 Mar 2017
Knew accumarray could be brought to bear, Guillaume, but it's always messy enough have to scratch head too much when time constrained... :)
Well, the first instance of accumarray is very much equivalent to your histc and they're probably the same speed.
The second instance is indeed messy, and I'm not convinced that using accumarray to generate cell arrays that are then converted to matrices is very efficient. Hence, why I then offered the loop option which may actually be faster, and certainly easier to understand.
Meghan Rochford
le 16 Mar 2017
Modifié(e) : Meghan Rochford
le 16 Mar 2017
dpb
le 16 Mar 2017
"...why I then offered the loop option which may actually be faster, and certainly easier to understand."
Indeed, it dawned on me that the loop over the bins was equivalent to a direct loop over the array while writing the posted answer but had it tested and with the time constraint of an appointment in town decided better just leave good-enough alone.
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!