Quick way to see if a struct has an equal value in an array of a struct of the same type

52 views (last 30 days)
I am wondering if there a quicker way of checking if a struct has an equal value in an array of structs of the same type. i'm currently doing this
function res = isUnique(nodeList, node)
for n = 1 : length(nodeList)
res = isequal(nodeList(n).state,node.state);
if res
res = false;
return;
end
end
res = true;
end
I tried just calling isequal with : to see if could be vectorized and that didn't seem to work. I think it was trying to compare that value to see if it equaled every value in the array which is not the case. Any help would be appreciated. I've been performance tuning my program and the isequal line accounts for 95% of my runtime. Any suggestions related to improving that are also welcome.
EDIT: I realized I left out an important detail. state is a 3x5 double

Answers (2)

Image Analyst
Image Analyst on 12 Nov 2019
Did you try something like (untested):
allNodes = [nodeList.state] % List of states from every structure all in one vector.
numMatches = sum(allNodes ==node.state)
allNodes ==node.state will give you a vector of false, where allNodes does not match node.state, and true where it does. sum() merely counts up the number of matches.

Walter Roberson
Walter Roberson on 12 Nov 2019
function res = isUnique(nodeList, node);
res = ismember(node.state, [nodeList.state])
end
Nowever this would need to change if state is a vector or array or character vector instead of a numeric scalar.
  3 Comments
Walter Roberson
Walter Roberson on 12 Nov 2019
Edited: Walter Roberson on 12 Nov 2019
function res = isUnique(nodeList, node)
node_state_row = reshape(node.state, 1, 15);
list_state_rows = reshape(cat(3, nodeList.state), 15, []).';
res = ismember(node_state_row, list_state_rows, 'rows');
end
Note: this code will not work if there can be nans.
Christian Hawley
Christian Hawley on 12 Nov 2019
that is taking a longer time to run than the previous solution because it's not doing what it should be doing. My understanding of ismember is that it looks in the list to see if the there is a match by a scrolling window approach. This causes more matches than there should be resulting in a longer runtime of the program.

Sign in to comment.

Categories

Find more on Structures in Help Center and File Exchange

Products


Release

R2017a

Community Treasure Hunt

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

Start Hunting!