How to dynamically create a struct?

I want to create a struct with the number of fields decided based on some user input. What's a good way of doing this? Or should I be using a cell or matrix instead?
Thanks

 採用された回答

KSSV
KSSV 2017 年 2 月 1 日

1 投票

a = struct ;
for i = 1:10
a(i).x = i ;
a(i).y = i+1 ;
end
It depends on how your structure is.

3 件のコメント

Keith Lewis
Keith Lewis 2017 年 2 月 1 日
Thanks, it's close to what I want to do.
What I'm doing is running a model of cyclist travel times along a road. I have a simulink simulation to do this, and I will run it perhaps 1000 times.
Then I want to save the time that each cyclist gets to each intersection along the road. The user will define the number of cyclists (times the model is run) and the number of intersections.
So the a(i) I guess would be for my cyclists, with the i being the cyclists' id number. But how can I create more fields based on the user input?
So like if there are 2 intersections, a.x and a.y is fine. But what if there's 50 intersections? How can I make it handle any number of intersections?
KSSV
KSSV 2017 年 2 月 1 日
a = struct ;
for i = 1:10
for j = 1:10
a(i).x(j) = rand ;
a(i).y(j) = rand+1 ;
end
end
Walter Roberson
Walter Roberson 2017 年 2 月 1 日
Index a cell array or multidimensional array. x(intersectionnumber, visitnumber)

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

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2017 年 2 月 1 日

0 投票

TheStructure = cell2struct( cell(1, length(NamesCell)), NamesCell, 2 )

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by