New Variables & Name in loop

3 Ansichten (letzte 30 Tage)
ML Noob
ML Noob am 26 Apr. 2021
Bearbeitet: ML Noob am 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;
0.5070;
0.5047;
0.4878;
0.4673;
0.4770;
0.4695;
0.4676;
0.4671;
0.4698;]
%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 ];
rng(42)
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
end
  1 Kommentar
Adam Danz
Adam Danz am 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.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

John D'Errico
John D'Errico am 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.

Kategorien

Mehr zu Cell Arrays finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by