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

조회 수: 54 (최근 30일)
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

답변 (2개)

Image Analyst
Image Analyst 2019년 11월 12일
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.
  댓글 수: 1
Christian Hawley
Christian Hawley 2019년 11월 12일
I tried this and it didn't work. state is a 3x5 double so it just kinda appended things a bunch of times.

댓글을 달려면 로그인하십시오.


Walter Roberson
Walter Roberson 2019년 11월 12일
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
Walter Roberson
Walter Roberson 2019년 11월 12일
편집: Walter Roberson 2019년 11월 12일
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 2019년 11월 12일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

태그

제품


릴리스

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by