フィルターのクリア

How to insert a int value into the name of a variable (for loop)

20 ビュー (過去 30 日間)
Duncan Wright
Duncan Wright 2017 年 9 月 1 日
コメント済み: Duncan Wright 2017 年 9 月 1 日
I'm trying to iterate throw these variable names in a for loop, here's my code:
form= 'dd-mmm-yyyy HH:MM:SS';
for i = 1:15
yearfrac=vpa(string([data_v3_data.b [INSERT i here] date]),10);
year = double(fix(yearfrac))
day = double(yearfrac-year)
a = datestr(datenum(year,1,1)+day*365)
data_v3_data.b + [INSERT i here] + date = datenum(a,form)
end
[INSERT i here] indicates where I would like the integer (1:15) to appear. I have a list of variables named:
data_v3_data.b1date
data_v3_data.b2date
data_v3_data.b3date
data_v3_data.b4date
etc etc..
Thanks !
  2 件のコメント
Adam
Adam 2017 年 9 月 1 日
Stephen23
Stephen23 2017 年 9 月 1 日
編集済み: Stephen23 2017 年 9 月 1 日
[INSERT i here]
tells us that you want an index. So why not use a real indexing instead of trying to write slow complicated code and pointlessly forcing meta-data (the index) into some names?
Indexing is fast and very efficient. Use it.

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

採用された回答

Stephen23
Stephen23 2017 年 9 月 1 日
編集済み: Stephen23 2017 年 9 月 1 日
data(1).date = ...
data(2).date = ...
data(3).date = ...
data(4).date = ...
This makes it trivially easy to access the data using indexing, which is fast and efficient, e.g. the second date:
data(2).date
Not only that you can very conveniently convert any field into a comma-separated list, which makes it simple to join the field values together into one array, e.g. to put all the dates into one cell array:
out = {data.date}
or to assign them in exactly the same way.
While it is possible to define structure fieldnames dynamically, in your case (you proposed numbered field names) it serves no purpose whatsoever and will only make your code slow and complicated.
Writing neat efficient MATLAB code is easy, once you avoid bad design decisions like putting meta-data into field or variable names:

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by