frequently used function for table variable

2 ビュー (過去 30 日間)
Rajesh Patel
Rajesh Patel 2021 年 6 月 7 日
コメント済み: Rajesh Patel 2021 年 6 月 8 日
I have a table with many temperature variables in C and I wanted to convert it into F using fuction. So I created following but it does not seems to work. Any way to create a function which are kind of common conversion which can be used again and again.
function Table_CtoF(T,OldVariable,NewVariable)
T.(NewVariable) = (T.(OldVariable)*9/5)+32;
end

採用された回答

Star Strider
Star Strider 2021 年 6 月 7 日
I am not certain what ‘T’ looks like.
Something like this would work —
T = table(randi([-40 40],5,1),'VariableNames',{'OldVariable'})
T = 5×1 table
OldVariable ___________ -6 11 37 -12 -34
T.NewVariable = Table_CtoF(T)
T = 5×2 table
OldVariable NewVariable ___________ ___________ -6 21.2 11 51.8 37 98.6 -12 10.4 -34 -29.2
function NewVariable = Table_CtoF(T)
NewVariable = (T.('OldVariable')*9/5)+32;
end
The single quotes are important when using this sort of variable addressing.
  10 件のコメント
dpb
dpb 2021 年 6 月 8 日
T.New = (T.(Old)*9/5)+32;
should be
T.(New) = (T.(Old)*9/5)+32;
You created the variable "New", not the one of the string value in variable New
Rajesh Patel
Rajesh Patel 2021 年 6 月 8 日
My bad. It works now. Thanks to all of you for great suggestions and solutions.

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

その他の回答 (1 件)

dpb
dpb 2021 年 6 月 7 日
Don't pass a table to your function, have it accept numeric inputs and return same; then just call it with the table names. Much more generic/useful that way.
>> which -all C2F
C:\Users\Duane\Documents\MATLAB\Utilities\C2F.m
>> type C2F
function F=C2F(C)
% convert degree C to F
F=1.8*C+32;
end
>>
Usage in your case would be something like
T.F=C2F(T.C);
if your table is T and the centigrade temperature variable is "C"
I'd be more tempted to use something like
T.C=C2F(T.C); % store temperature F in original variable
ixC=find(matches(T.Properties.VariableNames,'C')); % find which variable index it is
T.Properties.VariableNames(ixC)='F'; % label it as 'F' instead
so as to not carry but the one temperature variable.

カテゴリ

Help Center および File ExchangeWhos についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by