When you have different values assigned to different strings, how can you use these values in a loop?
1 回表示 (過去 30 日間)
古いコメントを表示
I want to make a loop and do a few things inside this loop, but none of them work yet. Part of it has to concern with months, for the example I will just use january and february:
jan = 1:31;
feb = 32:59;
First I want to make an empty matrix to fill later:
jan_mat = nan(length(jan),10)
Important is that I want to have a name including jan so I can easily find it back later. Another important thing is that I need the value of the length of jan. This formula works, but I want to have it in a loop so I don't have to define it for every month seperately.
What I tried:
B = {'jan','feb'}
This gives
B(1) = 'jan'
and
B{1} = jan.
I thought 'I need the second' so I define
C{i} = [B{i} '_mat']
This seems to work and gives
C(1) = 'jan_mat'
and
C{1} = jan_mat
I would think I could just write:
for i=1:2
C{i} = [B{i} '_mat']
C{i} = nan(length(B{i}),10)
end
But this fails to work. Can anybody explain how I can get what I want?
0 件のコメント
採用された回答
Adam
2015 年 1 月 8 日
編集済み: Adam
2015 年 1 月 8 日
Use a struct to hold all the months and something like the following:
months = { 'jan', 'feb',...'dec' }
monthDays.jan = 1:31;
monthDays.feb = 32:59;
% etc
for i = 1:numel( months )
monthVals.( months{i} ) = nan( numel( monthDays.( months{i} ) ), 10 );
end
There are almost certainly better ways to create the month days that just 12 lines of hard-coding the numbers like that, but that part is a 1-time constant setup so not really important. The key is that you can use dynamic field names far more easily than dynamic variable names (and it keeps your workspace tidy by grouping them in a single struct or 2 structs in this case).
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Structures についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!