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에서 Whos에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!