Apply function (str2double) to each element in a timetable

5 ビュー (過去 30 日間)
Luca Amerio
Luca Amerio 2018 年 4 月 16 日
回答済み: Peter Perkins 2018 年 4 月 19 日
Hi
I have a timetable where some numeric fields are stored as strings and other as 1x1 cell arrays of strings (of char array to be precise).
I tried apply @str2double (since it supports both the conversion from '123' and {'123'}) element-wise to them using both rowfun and varfun, but neither of them worked since the row/column are passed as inputs all together.
How can I apply a function element wise to the elements of a (time)table?

回答 (1 件)

Peter Perkins
Peter Perkins 2018 年 4 月 19 日

varfun does this with no problem:

>> t = table(["123";"456"],{'789'; '012'},[345;678])
t =
  2×3 table
    Var1     Var2     Var3
    _____    _____    ____
    "123"    '789'    345 
    "456"    '012'    678 
>> t2 = varfun(@str2double,t,'InputVariables',@(x) ~isnumeric(x))
t2 =
  2×2 table
    str2double_Var1    str2double_Var2
    _______________    _______________
          123                789      
          456                 12      

The problem now is how to get those converted values back into the original table. Because () and {} subscripting are assigning to "elements", and not to "whole variables", you can't convert a variable's type with, for example, t(:,1:2) = t2. Instead:

t.Var1 = t2.Var1;
t.Var2 = t2.Var2;

or perhaps

t = [t2 t(:,3)]

カテゴリ

Find more on Tables in Help Center and File Exchange

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by