Fastest way to cycle through a structure for a number

1 回表示 (過去 30 日間)
Will Kinsman
Will Kinsman 2016 年 8 月 1 日
コメント済み: Stephen23 2016 年 8 月 2 日
given: a structure and a double
return: the index of a structure that has that number
data:
structure(1).val = 50
structure(2).val = 47
structure(3).val = 22
given: structure, 50
return: 1
given: structure, 22
return: 3
% my attempt
function y = return_struct_index(structure,inputval)
for i = 1:length(structure)
if structure(i).val==inputval
y = i;
return
end
end
y = [];
This is rather slow and comes in at about 2.5 seconds for 1000 iterations for my code. I know for a fact there is a faster way to do this but haven't been able to track it down. Obviously I haven't vectored my function. I have also tried converting the structure to a cell array and then vectoring the solution, but the conversion makes it even slower.
Help greatly appreciated!!
Will
  1 件のコメント
Stephen23
Stephen23 2016 年 8 月 2 日
If there are non-scalar arrays in the field val:
S(1).val = 50;
S(2).val = 47;
S(3).val = [23,5];
fun = @(n)find(arrayfun(@(s)any(s.val(:)==n),S));
>> fun(22)
ans =
Empty matrix: 1-by-0
>> fun(23)
ans =
3

サインインしてコメントする。

採用された回答

James Tursa
James Tursa 2016 年 8 月 1 日
編集済み: James Tursa 2016 年 8 月 1 日
result = find([structure.val]==value);
E.g.,
>> structure(1).val = 50;
>> structure(2).val = 47;
>> structure(3).val = 22;
>> find([structure.val]==50)
ans =
1
>> find([structure.val]==47)
ans =
2
>> find([structure.val]==22)
ans =
3
>> find([structure.val]==99)
ans =
Empty matrix: 1-by-0
  1 件のコメント
Will Kinsman
Will Kinsman 2016 年 8 月 1 日
編集済み: Will Kinsman 2016 年 8 月 1 日
thanks so much. massively improved my programs performance by about 10 minutes. run time per 1000 iterations came in at about .5 seconds

サインインしてコメントする。

その他の回答 (1 件)

Azzi Abdelmalek
Azzi Abdelmalek 2016 年 8 月 1 日
s(1).val = 50
s(2).val = 47
s(3).val = 22
find([s(:).val]==50)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by