Add table variable and assign constant string

24 ビュー (過去 30 日間)
Bryan Wilson
Bryan Wilson 2016 年 11 月 7 日
コメント済み: Peter Perkins 2016 年 11 月 10 日
I want to add a new variable to a table and assign a string to that variable for every row of the table.
T = table({'A';'B';'C'},[1;2;1],[6;7;5],...
'VariableNames',{'Section' 'Data1' 'Data2'})
newString = "Project A"
T.newVar(:) = {newString}
T =
Section Data1 Data2 newVar
_______ _____ _____ __________
'A' 1 6 [1x0 cell]
'B' 2 7 [1x0 cell]
'C' 1 5 [1x0 cell]
What I'd like is....T=
Section Data1 Data2 newVar
_______ _____ _____ __________
'A' 1 6 'Project A'
'B' 2 7 'Project A'
'C' 1 5 'Project A'

採用された回答

Walter Roberson
Walter Roberson 2016 年 11 月 7 日
T.newVar = repmat({newString}, size(T,1), 1)
  2 件のコメント
Guillaume
Guillaume 2016 年 11 月 7 日
編集済み: Guillaume 2016 年 11 月 7 日
Well, actually, if string means the new string type introduced in 2016b (as the double quotes would indicate), then:
T.newVar = repmat(string('Project A'), height(T), 1)
Bryan Wilson
Bryan Wilson 2016 年 11 月 8 日
Typo - meant to use single quotes.

サインインしてコメントする。

その他の回答 (1 件)

Peter Perkins
Peter Perkins 2016 年 11 月 9 日
This slight change to the original code also works:
>> T.newVar(:,1) = newString % note the ",1"
T =
Section Data1 Data2 newVar
_______ _____ _____ ___________
'A' 1 6 "Project A"
'B' 2 7 "Project A"
'C' 1 5 "Project A"
  2 件のコメント
Guillaume
Guillaume 2016 年 11 月 10 日
That is interesting. Is it documented anywhere?
It also does not make sense that one syntax works and the other doesn't since for a column vector (:) and (:, 1) should be exactly equivalent.
Peter Perkins
Peter Perkins 2016 年 11 月 10 日
Using (:,1) to create a new column vector is standard MATLAB syntax, and is sometimes needed to make sure your result becomes a column vector.
The issue here is that newVar doesn't yet exist as a column vector when you make the assignment. But in a table, it does seem like it shouldn't be needed. I will make a note to have that looked into.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by