# Local macro in STATA?

3 views (last 30 days)
Hoi Dinh on 20 Apr 2021
Answered: Bjorn Gustavsson on 20 Apr 2021
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,

Bjorn Gustavsson on 20 Apr 2021
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