MATLAB Answers

New Variables & Name in loop

1 view (last 30 days)
ML Noob
ML Noob on 26 Apr 2021
Edited: ML Noob on 26 Apr 2021
I am trying to loop through a 10 row variable of covariances ('T') and use the values to simulate data following the covariance.
Each sim iteration (a 5x2 vector 'X') has to have a different variable name attached to it. So ithey would be X_1 to X_10 (or something like that). I need them to be this way as some will have to operate on individually in the future.
How would I fix the loop to accomplish this? New to Matlab. Thanks!
Edit: I realize this is a no no however, there is a specific reason it would be easier this way. Otherwise, an appended array would work but then how would I be able to do that?
T = [0.4980;
%Sim Observations of the specified covariances in T
count = 0
for i = 1:length(T)
sig = T(count+1)
n = 5;
d = 2;
Sigma = [ 1 sig ; ...
sig 1 ];
X = randn(n, d) * chol(Sigma);
X = randn(n, d);
X = bsxfun(@minus, X, mean(X));
X = X * inv(chol(cov(X)));
X = X * chol(Sigma);
count = count+1
  1 Comment
Adam Danz
Adam Danz on 26 Apr 2021
This is a big no-no in programming. Why not to use dynamic variable naming.
Instead, store the values within an array or a table. With a table, you can assign any variable name you want with a column of data.

Sign in to comment.

Answers (1)

John D'Errico
John D'Errico on 26 Apr 2021
Don't do it.
Your code will be the worse for it. Instead, learn to use arrays! Use cell arrays, rgular arrays, structs, there are all sorts of arrays you can use. Trying to name your variables like that is using a spreadsheet mentality when you want to learn to use a real programming language.


Community Treasure Hunt

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

Start Hunting!