Apply function (str2double) to each element in a timetable

6 visualizzazioni (ultimi 30 giorni)
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?

Risposte (1)

Peter Perkins
Peter Perkins il 19 Apr 2018

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)]

Categorie

Scopri di più su Tables in Help Center e File Exchange

Tag

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by