필터 지우기
필터 지우기

How to create a variable named from string

조회 수: 19 (최근 30일)
Kasper Buchardt
Kasper Buchardt 2020년 12월 3일
댓글: Ameer Hamza 2020년 12월 3일
I'm loading data from an excel file, with multiple objects. I want to create a variable (matrix) named after the object, containing processed data.
So this is basically what I have:
test_data.name(i) = 'Object 2-1'
This is what i want:
Object_2_1 = [3 4 5 etc.];
This means i both needs to replace "space" and "-" with "_" and then name/create the variable. Can someone please help me on how to approach this challenge?
  댓글 수: 4
Stephen23
Stephen23 2020년 12월 3일
which states "A frequent use of the eval function is to create sets of variables such as A1, A2, ..., An, but this approach does not use the array processing power of MATLAB and is not recommended. The preferred method is to store related data in a single array."
and also this page, which gives plenty of reaons why this approach to writing code should be avoided:
Kasper Buchardt
Kasper Buchardt 2020년 12월 3일
Thank you both very much, both @Deepak for providing a possible answer to my question and to @Stephen for guidance towards another solution which is more correct.

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

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 12월 3일
Although possible, it is a terrible (cannot emphasize enough) coding practice to create variable names dynamically: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval. Avoid it. Either use struct, tables or arrays. It will make your code much efficient and easy to debug.
For example, you can use the test_data struct to contain names as well as data.
test_data(i).name = 'Object 2-1';
test_data(i).data = [3 4 5 etc.];
  댓글 수: 7
Kasper Buchardt
Kasper Buchardt 2020년 12월 3일
That sounds very interresting and is definitly something i will look into and experiment with.
Thank you yet again.
Ameer Hamza
Ameer Hamza 2020년 12월 3일
I am glad to be of help! :)

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by