# Local macro in STATA?

5 ビュー (過去 30 日間)
Hoi Dinh 2021 年 4 月 20 日

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,

サインインしてコメントする。

### 回答 (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

サインインしてコメントする。

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by