How do I add a known vector to an existing matrix in a loop?

조회 수: 1 (최근 30일)
Jorge Gonçalves
Jorge Gonçalves 2016년 2월 24일
편집: Stephen23 2019년 6월 19일
I have 14 vectors from x1 to x14. I want to creat a loop that allows me to add a known vector to the previously created matrix, for example:
I have the matrix: in= [x1; x2; x3; x4; x5]
Now I want to create a loop that adds the other vectors to the matrix in. What I wrongly did was this:
for j=6:13
ta= xj; inj=[in; xj];
How do I put de x6, x7, x8 and so on into the matrix in6, in7, in8 and so on? My problema is getting the vectors by their names to work with them... The ta is a vector that I'll need in the problem.
  댓글 수: 3
Jorge Gonçalves
Jorge Gonçalves 2016년 2월 24일
These variables, x1 to x14 are vectors of wind power values sent to me. So you're saying that the solution may be creating a matrix M that countains all the 14 vectors and then adding row by row to new matrix?
Stephen23
Stephen23 2016년 2월 24일
The core question is "how are these variables generated?"
If they are loaded from file data then they can be easily loaded into one variable. If they are hardcoded then change the code.

댓글을 달려면 로그인하십시오.

답변 (2개)

James Tursa
James Tursa 2016년 2월 24일
편집: James Tursa 2016년 2월 24일
There is a way to do this using the eval function, BUT you are strongly advised against this approach. Rather, you should be using cell arrays or nD matrices for this. E.g., use x{1}, x{2}, etc instead of x1, x2, etc. That way you can get at them easily in a loop as you need. E.g., see this link:
  댓글 수: 1
James Tursa
James Tursa 2016년 2월 24일
편집: James Tursa 2016년 2월 24일
If you have been sent these variables x1, x2, etc by someone else, then please advise them to modify their code! In the meantime, you can do this up front to put them into a manageable cell array that can be easily indexed in a loop:
n = number of variables
x = cell(n,1);
for k=1:n
x{k} = eval(['x' num2str(k)]);
end

댓글을 달려면 로그인하십시오.


Stephen23
Stephen23 2016년 2월 24일
편집: Stephen23 2019년 6월 19일

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by