New Variables & Name in loop

3 次查看(过去 30 天)
ML Noob
ML Noob 2021-4-26
编辑: ML Noob 2021-4-26
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 个评论
Adam Danz
Adam Danz 2021-4-26
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.

请先登录,再进行评论。

回答(1 个)

John D'Errico
John D'Errico 2021-4-26
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.

类别

Help CenterFile Exchange 中查找有关 Cell Arrays 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by