将带有逗号和空格的单元格字符串转换为向量

Convert cell string with commas and spaces to vector

我尝试转换单元格 x:

x(1,:) = {'35,35, ,35'}; 
x(2,:) = {'40,40,30,40'};
x(3,:) = {'10, , ,'};

到矩阵:

R = cell2mat(cellfun(@str2num,x,'un',0));

但结果省略了第一行:

 R =

    40    40    30    40

但我期待:

 R =

    35    35     0    35
    40    40    30    40
    10     0     0     0

如何做到这一点? 谢谢!

您必须手动完成。请尝试使用此脚本来实现您正在搜索的内容

clear
clc
x(1,:) = {'35,35, ,35'}; 
x(2,:) = {'40,40,30,40'};

for i = 1: length(x)
   v1 = split(x(i),",");
   for j = 1:length(v1)
       if length(str2num(v1{j})  )==0
            oo(j)=0;
       else
      oo(j)= str2num(v1{j});
       end
   end
    R(i,:) = oo(1,:);
end

Split x by ,, convert to double using str2double and fill the missing values0 如下:

R = fillmissing(str2double(split(x,',')),'constant',0);
>> R
R =
   35   35    0   35
   40   40   30   40
   10    0    0    0

注意:避免使用str2num since it is implemented using eval. Read the security considerations and unintended side effects of using that in the documentation获取详细信息。