Make a for loop for the following code
1 次查看(过去 30 天)
显示 更早的评论
I am estimating the probabilities over time.
for example, my data matrix is 6 by 5 (where 6 is the number of simulations and 5 is the number of time periods).
data = [2, 2 , 1, 1, 1, 1; 2, 2 , 1, 1, 1, 2; 2, 2 , 1, 2, 1, 2; 2, 2 , 1, 2, 1, 2; 2, 3 , 2, 2, 1, 2]
States = unique([data(:,1); data(:,2)]) % Find the unique rows of A based on the data in the first two columns.
[TFinitial, fromstateAge27] = ismember(sequence(:,3), States) % logical arrays
[TF25, tostateAge27] = ismember(sequence(:,4), States) % logical array
went_from_to_countAge27 = accumarray( [fromstateAge27(:), tostateAge27(:)], 1, []) % frequency of transitions from one state to another
went_from_to_probAge27 = went_from_to_countAge27 ./ sum(went_from_to_countAge27) % probability of transition from one state to another
Now I want to make a for loop that runs the above code for each column of matrix "data".
For the above code (column 1 to 2), my output is "went_from_to_probAge27 "
for column 2 to 3, my output will be "went_from_to_probAge28"
from column 3 to 4, my output will be "went_from_to_probAge29" and so on.
3 个评论
Rik
2021-2-16
Yes, by using the method Jan shows below. That way you can still use indexing to access the data, instead of having to generate the variable name every time you want use the variable.
采纳的回答
Jan
2021-2-16
Naming a variable "went_from_to_probAge27" hides important information in the name. There this information can be accessed by really awkward methods only. See TUTORIAL: why and how to avoid EVAL
Use arrays instead. Because here you need 27 as data, a struct array would be efficient:
Data(1).Age = 27;
[TFinitial, Data(1).fromstate] = ismember(sequence(:,3), States);
[TF25, Data(1).tostate] = ismember(sequence(:,4), States)
...
Does this help to solve your problem?
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!