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
댓글 수: 0
답변 (2개)
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.
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
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!