Use text in table to make variables

조회 수: 19 (최근 30일)
David Slater
David Slater 2021년 1월 22일
댓글: David Slater 2021년 1월 23일
I have a table, T; the first column contains text enclosed in single quotes, and the second column contains scalar numbers:
Symbol Value
1 'Z1' 3
2 'Z2' 4
How can I get Matlab to create variables from the Symbols and assign the Values to them? ie
Z1=3
Z2=4
I could convert T.Symbol into a string vector:
T.Symbol =s,
but how can I convert s into variables, without having to type each variable manually? (In reality, my table contains many rows, and I have more than one table.)

채택된 답변

Walter Roberson
Walter Roberson 2021년 1월 22일
That is not recommended. For example, how would you expect your code to be able to proceed if one of the symbols was 'T' and so you assigned a numeric value to T, overwriting T's usage as a table?
T = table({'Z1'; 'Z2'}, [3;4], 'VariableNames', {'Symbol', 'Value'})
T = 2x2 table
Symbol Value ______ _____ {'Z1'} 3 {'Z2'} 4
vars = cell2struct(num2cell(T.Value), T.Symbol, 1)
vars = struct with fields:
Z1: 3 Z2: 4
vars.Z2
ans = 4
  댓글 수: 1
David Slater
David Slater 2021년 1월 23일
This works. I can now use vars.Z1 and vars.Z2 in place of the variables Z1 and Z2 in the remainder of my script. to save time, in reality I have named the structure with a single letter. This makes a difference, because there are many more than two variables in my script. I also followed the link to the tutorial, and and I found it helpful. Many thanks. Answer accepted.

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

추가 답변 (1개)

dpb
dpb 2021년 1월 22일
Do NOT even think about doing this.
  댓글 수: 1
David Slater
David Slater 2021년 1월 23일
An explanation of why not would have been helpful. Walter Robinson has given me an acceptable solution and explained why this is not recommended.

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

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by