MATLAB Answers

Local macro in STATA?

조회 수: 3(최근 30일)
Hoi Dinh
Hoi Dinh 2021년 4월 20일
답변: Bjorn Gustavsson 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)


Bjorn Gustavsson
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;
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';
you can also far easier make this code independent of the value of n_vars.

Community Treasure Hunt

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

Start Hunting!

Translated by