how to convert a table to vectors where each vector takes the name of the column in the table

조회 수: 43 (최근 30일)
if I have a table T where each column has a header, how can i convert the table to vectors where each vector takes the respective name in the table? so if the table has 3 columns abc,xyz, wzt . how can I generate vectors that are called abc,xyx,and wzt. (it is a sample example but my table is much larger )
  댓글 수: 1
Stephen23
Stephen23 2017년 2월 8일
편집: Stephen23 2017년 2월 8일
"how can I generate vectors that are called abc,xyx,and wzt"
Although popular with beginners, doing this makes code slow, buggy, hard to read, difficult to debug, and has other disadvantages:

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

채택된 답변

Guillaume
Guillaume 2017년 2월 8일
Assuming you're are talking about matlab tables. What would be the advantage of going from an easy, clear, debugger and optimiser friendly way of referencing columns to a more complicated, slow, bug-prone dynamically named individual variables?
You can already access your individual vectors as
tablename.xyz
tablename.abc
Why can't you continue to do so?
In other words, don't do it. Yes, it's possible but there's no advantage and plenty of downsides (the editor won't be able to see syntax errors, the code will run slower because the optimiser won't be able to tell what is going on, the code will be longer, etc.)
  댓글 수: 1
Viktor G.
Viktor G. 2020년 2월 28일
But what if I don't know which variables will I need, so I want to be able to choose late on with the input option? Wouldn't it be better if I just imported the table as separate column vectors?

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

추가 답변 (1개)

Adam
Adam 2017년 2월 8일
편집: Adam 2017년 2월 8일
Why would you need your vectors named that? How are you planning to work with these vectors afterwards given that their names come from a table rather than simply being hard coded into the program so that you can actually refer to them.
Use a struct if you really need to do this e.g.
s.( header1 ) = ...
s.( header2 ) = ...
then if header1 = 'abc' and header2 = 'xyz' you will end up with a struct containing fields abc and xyz which you can later refer to in the same way.
I don't use tables so I don't know off-hand the specifics of extracting headers and columns from them, but I assume you know that. I could look it up and try out on my command line, but then you can also do that so there'd be no point me doing it!
  댓글 수: 1
Peter Perkins
Peter Perkins 2017년 2월 8일
table2struct(t,'ToScalar',true) will do that, but honestly, there's little reason to want to. As Guillaume points out, tables provide the same "dot-varName" syntax as a scalar struct, plus a lot more.

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

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by