Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/258.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Matlab 如何将具有混合数据类型的表转换为单个数据类型?_Matlab - Fatal编程技术网

Matlab 如何将具有混合数据类型的表转换为单个数据类型?

Matlab 如何将具有混合数据类型的表转换为单个数据类型?,matlab,Matlab,我在Matlab中定义了一个表,它是字符串和整数的混合体,即 A B C D D ---------- --- --- --- --- 1.0002e+05 '2' '2' '1' '2' 1.0002e+05 '2' '1' '2' '2' 1.0

我在Matlab中定义了一个表,它是字符串和整数的混合体,即

    A             B         C         D         D
    ----------    ---       ---       ---       ---
    1.0002e+05    '2'       '2'       '1'       '2'   
    1.0002e+05    '2'       '1'       '2'       '2'   
    1.0002e+05    '2'       '2'       '1'       '1'   
    1.0003e+05    '2'       '2'       '2'       '1'   
    1.0003e+05    '2'       '2'       '3'       '1'   

多亏了一些数据清理,我知道唯一可以使用的就是整数数据。因此,如何将str2num
应用到表中,以便立即更新所有内容?

我怀疑可能有更干净的方法来执行此操作,但假设表名为
data

% Convert the data new table that contains the numeric data
conversion = array2table(cellfun(@str2num, table2cell(data(:, 2:end))));

% Copy the column names over
conversion.Properties.VariableNames = data.Properties.VariableNames(2:end);

% Delete the old columns
data(:, 2:end) = [];

% Concatenate the new table
data = [data conversion];

另一种方法是利用,它也适用于表

假设您的表
T
设置如下:

myvarnames = T.Properties.VariableNames;
for ii = 1:length(myvarnames)
    if iscell(T.(myvarnames{ii}))
        % If your table variable contains strings then we will have a cell
        % array. If it's numeric data it will just be in a numeric array
        T.(myvarnames{ii}) = str2double(T.(myvarnames{ii}));
    end
end
我们也可以使用(例如,
T=varfun(@str2double,T)
),但在这种情况下,它会出错,因为并非所有变量都是字符串。我假设是这种情况,但错误消息非常隐晦(
MATLAB:table:rowdimmensionsmatch
)。您可以通过一个块捕捉到这一点,但您有可能传递实际的维度不匹配,这是我不喜欢的。如果明确知道要传递哪些变量,也可以使用


varfun
还会令人烦恼地重命名传递的变量。诚然,只需要一行程序就可以修复它,但它仍然很烦人。

我认为表是一种以良好方式表示数据的方法。主要是因为你很容易遇到这样的麻烦。建议您使用另一种方法(可能使用单元格?),并且仅使用表格进行图形表示。然而,你可能有很好的理由这样做,所以这不是批评。作为一名Java程序员,我并不认为这种方法“不干净”或类似的东西。我猜这在使用用户定义类型时是相当标准的(意思是“用Matlab编写”,而不是基本类型,如double、int8等等)。@patrik表
和数据类型之间似乎没有太大的实际区别,但我不太明白如何让它工作。