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

52 ビュー (過去 30 日間)
Christian Hawley
Christian Hawley 2019 年 11 月 12 日
コメント済み: Christian Hawley 2019 年 11 月 12 日
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 Center および File ExchangeStructures についてさらに検索

タグ

製品


リリース

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by