Local macro in STATA?
조회 수: 3 (최근 30일)
이전 댓글 표시
in STATA: I can easily to use local maro to create sequence variables:
forvalues i=1(1) 8 {
gen x_`i' = 0
}
Output: variables : x_1 , x_2,.., X_8 = 0
How could I create the same sequence of variables in MATLAB: ( inside the loop)
Thanks,
댓글 수: 0
답변 (1개)
Bjorn Gustavsson
2021년 4월 20일
That is generally a poor programming pattern (read this as: "This is a really poor idea!"). You should aim to write your code such that it is able to handle cases where the upper limit is variable. When that is the case, you will have to find out how many x_i you have and adjust accordingly, that is cludgy. Try to get used to vectorizing your programming, in this case this might mean using a matrix for x, or a cell-array. Something like this:
n_vars = 8;
for i1 = n_vars:-1:1
x{i1} = 0;
end
Then you can put whatever you need into each separate cell:
for i1 = 1:n_vars
if isprime(i1)
x{i1} = randn(i1^2);
elseif mod(i1,2) == 0
x{i1} = 'divisible by 2';
end
end
you can also far easier make this code independent of the value of n_vars.
HTH
댓글 수: 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!