필터 지우기
필터 지우기

How do you use one vector to name another vector?

조회 수: 1 (최근 30일)
Danny
Danny 2014년 12월 16일
댓글: Star Strider 2014년 12월 18일
If you have three vectors: vect1 = [1 2], vect2 = [4 5], and vect3 = {'name1';'name2'}, how do I name vect1 and vect2 using the contents of vect3, i.e., how do I obtain
name1 = [1 2]
name2 = [4 5].
I have found one solution where the function assignin is used but I was wondering if there may be a more streamlined/simpler solution?
  댓글 수: 1
Image Analyst
Image Analyst 2014년 12월 16일
편집: Image Analyst 2014년 12월 16일
And if you don't know the names in advance so that you can hard code in the variable name, and you have to create the variable dynamically from strings, then how are you going to be able to refer to name1 and name2 later in your code? Like you said, there is a simpler way to do whatever it is you want to do, and that way does not involve doing what you asked for. I completely agree with Star Strider there. Just let us know what you really need to accomplish and, rather than suggest a bad method like this yourself, let us advise you how to get you there.

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

채택된 답변

Star Strider
Star Strider 2014년 12월 16일
What you want to do has to be near the top of everyone’s ‘Don’t Do This!’ list.
But if you must, this works:
vect1 = [1 2];
vect2 = [4 5];
vect3 = {'name1';'name2'};
for k1 = 1:length(vect3)
eval([vect3{k1} sprintf(' = vect%-d',k1)]);
end
name1
name2
  댓글 수: 4
Star Strider
Star Strider 2014년 12월 18일
The eval function has its uses. I Answered one Question a while ago where the OP had a number of 2D matrices output by a FORTRAN routine that gave sequential names to each matrix. The OP wanted to use a loop with eval to concatenate them to a single three-dimensional array.
Perhaps Danny has the reverse situation, in which he has to write 2D arrays to be read by another routine that won’t read MATLAB multidimensional arrays. That would be a perfectly legitimate reason to do what he wants to do.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by