How to access randomly selected index in nested structures

I want to access intexes that are into a structure that are nested within another structure. I have this code working through every ith element, and I want to add to the code randomly selected values j. In my case j is from 1 to 365 day of the year.
for i=1:n
fileName=structName(i).nestedStructName(j).name
end
Any ideas?
Darina

 採用された回答

Amit
Amit 2014 年 1 月 28 日

0 投票

Try something like this:
for i=1:n
X = fieldnames(structName);
n = length(X);
fileName=structName(i).(X{randi(n)}).name;
end
The issue is that your nestedStucture has multiple fields and you wanna pick one randomly.

1 件のコメント

Darina
Darina 2014 年 2 月 9 日
Thanks a lot! Works perfectly!

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

その他の回答 (2 件)

Mischa Kim
Mischa Kim 2014 年 1 月 28 日

0 投票

How about
fileName=structName(i).nestedStructName(randi(365,1)).name
Is this what you are looking for?

7 件のコメント

Darina
Darina 2014 年 1 月 28 日
Hey thank you! But it keeps saying Reference to non-existent field 'demand_pattern'. I tried different things and I only get this error.
Mischa Kim
Mischa Kim 2014 年 1 月 28 日
Does nestedStructName have 365 elements?
Darina
Darina 2014 年 1 月 28 日
yes, why ?
Darina
Darina 2014 年 1 月 28 日
Could the problem be in this -> structName(i) has 1xn struct while for j there are nestedStructName1,...,nestedStructName365 each has 1x1 struct?
Mischa Kim
Mischa Kim 2014 年 1 月 28 日
Just before entering the for-loop add:
[rS, cS] = size(structName)
[rnS, cnS] = size(structName(rS).nestedStructName)
What do you get?
Darina
Darina 2014 年 1 月 28 日
[rS, cS] = size(allFileMin)
[rnS, cnS] = size(allFileMin(rS).demand_pattern)
the answer:
rS =
1
cS =
28
Reference to non-existent field 'demand_pattern'.
Error in Activity (line 136)
[rnS, cnS] = size(allFileMin(rS).demand_pattern)
Darina
Darina 2014 年 1 月 28 日
This happends because I only have nestedStructName1 to nastedStructName365 but not a single naestedStructName without index.

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

Shivaputra Narke
Shivaputra Narke 2014 年 1 月 28 日

0 投票

May this works,
for i=1:n j=1+round(364*rand(1)); fileName=structName(i).nestedStructName(j).name end

1 件のコメント

Darina
Darina 2014 年 1 月 28 日
Hm, no it still gives the same error.. -.-

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

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

製品

質問済み:

2014 年 1 月 28 日

コメント済み:

2014 年 2 月 9 日

Community Treasure Hunt

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

Start Hunting!

Translated by