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

카테고리

Help CenterFile Exchange에서 Tables에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by