Variable importing into code

조회 수: 1 (최근 30일)
Matt Brianik
Matt Brianik 2018년 1월 11일
댓글: Guillaume 2018년 1월 12일
Is there a way to import variables from work space into the code that genrrates them.
For example
x=20 random names
y=genvarname(x)
can i now import y into the code and use these variables
  댓글 수: 2
Stephen23
Stephen23 2018년 1월 12일
편집: Stephen23 2018년 1월 12일
Don't do that.
Use a structure, any other array (cell, ND numeric, etc) with indexing, or a table, etc.
Guillaume
Guillaume 2018년 1월 12일
I think that maybe you're asking the wrong question.
As others have said, creating dynamically named variables is a bad idea (for many reasons). There are other more reliable methods such as structures with dynamic fields or better a table if all these variables are the same size. And we can show you how to do that if that's indeed what you need to do.
However, the fact that you want to do this is puzzling. So what's your use case? It may be that you're approaching this completely the wrong way and a completely different approach would solve your problem more easily.

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

답변 (3개)

Star Strider
Star Strider 2018년 1월 11일
I would import ‘y’ as an array of some type (numeric, cell, table, etc.) and refer to the individual elements in your calculations. Dynamic variable creation is not considered good programming practice.

SRT HellKitty
SRT HellKitty 2018년 1월 11일
I think this is the answer that you are looking for. Basically you can use evalin or assignin to do this and I cannot think of a better way this can be done unless there is a more elegant solution using get_param/getVariable. It is not recommended to use evalin and assignin for the reasons listed in This FAQ page. So if this can be avoided, that would be best otherwise this should get the job done!
  댓글 수: 4
Matt Brianik
Matt Brianik 2018년 1월 11일
so what method would you suggest I do to accomplish this, I'm not a strong programmer and simpler is best?
Walter Roberson
Walter Roberson 2018년 1월 11일
Use a struct, or possibly a table(), or just second cell array with the same number of elements as the first and index it at corresponding locations.

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


Matt Brianik
Matt Brianik 2018년 1월 11일
Can you show an example, I'm having trouble grasping this?

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by