New Variables & Name in loop
조회 수: 3 (최근 30일)
이전 댓글 표시
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
2021년 4월 26일
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
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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Cell Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!