MATLAB Answers

Preserve Name of Indexed Variable for columns when creating a Table

조회 수: 3(최근 30일)
TS
TS 2021년 3월 24일
댓글: Walter Roberson 2021년 3월 24일
As title says i want to creat a table that contains different values.
If i write
T = table(Time,Data,Etc);
the names of the columns will be
Time Data Etc
BUT if i write
T = table(Time(1:50,:),Data(1:50,:),Etc);
the names of the columns will be
Val1 Val2 Val3
So my question is, how can i preserve the names of the variables when indexing them? I know there are some methods to do this by creating new variables with the indexed value or change the name of the columns with the properteries option. But this is an additional step i have to make and im lazy.

답변(1개)

Geoff Hayes
Geoff Hayes 2021년 3월 24일
TS - you can set the variable names when you create the table
T = table(Time(1:50,:),Data(1:50,:),Etc(1:50,:), 'VariableNames', {'Time', 'Data', 'Etc'});
  댓글 수: 4
Walter Roberson
Walter Roberson 2021년 3월 24일
No, when you index a variable, a temporary array is constructed. I talk about the process more in
When you pass Time(1:50,:) into a function, then it is not the case that MATLAB passes a pointer to the beginning of the array and passes the indices with something in the handling of the called code processing the indexes. That would get messy very quickly -- since the received variable might get indexed and passed into something else, so multiple layers of indexing information would have to get sent around if it was information about how to do the indexing that was being passed.
When you pass Time(1:50,:) into a function, the handling is the same as if you had passed Time + 1 into the function, or some other expression where passing variable and indexing information would not be enough even in principle. Instead, the Time(1:50,:) and Time + 1 cases are treated the same: the results of the expression are calculated, creating a new unnamed temporary variable, and the unnamed temporary is what is passed in. Either way the receiving function doesn't know the name of the expression because expressions do not have names.
The only time the receiving function can find out the name of the passed variable is if an entire named variable is passed, plain, with no calculations involved.
Indexing to read data is a function call in MATLAB: it returns the actual data, not a reference to a variable together with information about how you would index the variable if it turns out you need the information stored there.
(Indexing to write data is a function call in MATLAB too.)

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

Community Treasure Hunt

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

Start Hunting!

Translated by