Reference struct field with an index and not it's name

10 ビュー (過去 30 日間)
Daniel
Daniel 2017 年 6 月 23 日
コメント済み: Daniel 2017 年 6 月 23 日
I want to randomly reference different fields of a structure without naming the field, and ideally without using an if statement.
I currently have a structure like so:
s = struct;
s.field1 = {1; 2; 3; 4; 5};
s.field2 = {6; 7; 8; 9; 10};
I'm then generating a random number and want to access one of the fields depending on what the number is. E.g. if the random number is 1, access field1, if it's a 2, access field 2. I then want to be able to take specific numbers from within that field, so that I could get:
>> a = s.(2){3, 1} % (2) is the randomly generated number in this example
>> b = s.field2{3, 1}
>> a == b
ans =
logical
1
I know I can do this with an if statement, but I want to avoid if statements if possible. Is it possible to do this in Matlab, or not?

採用された回答

Stephen23
Stephen23 2017 年 6 月 23 日
編集済み: Stephen23 2017 年 6 月 23 日
You should use a non-scalar structure, and then this will be trivially easy:
s(1).field = [1; 2; 3; 4; 5];
s(2).field = [6; 7; 8; 9; 10];
N = randperm(numel(s),1);
s(N).field

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by