【问题标题】:Matlab - string containing a number and equal signMatlab - 包含数字和等号的字符串
【发布时间】:2015-09-15 04:34:09
【问题描述】:

我有一个数据文件,其中包含参数名称和值,它们之间有一个等号。是这样的:

A = 1234
B = 1353.335
C = 
D = 1

等号前后总是有一个空格。问题是一些变量没有像上面的“C”这样分配给它们的值,我需要清除它们。

我想将数据文件(文本)读入一个单元格,然后删除带有这些无效语句的行,或者只创建一个没有它们的新数据文件。

哪个更容易,但我最终会使用 textscan 命令将文件读入一个单元格。

值(数字)将被视为双精度。

请帮忙。

谢谢,

埃里克

【问题讨论】:

    标签: matlab file file-io


    【解决方案1】:

    试试这个:

    fid = fopen('file.txt'); %// open file
    x = textscan(fid, '%s', 'delimiter', '\n'); %// or '\r'. Read each line into a cell
    fclose(fid); %// close file
    x = x{1}; %// each cell of x contains a line of the file
    ind = ~cellfun(@isempty, regexp(x, '=\s[\d\.]+$')); %// desired lines: space, numbers, end
    x = x(ind); %// keep only those lines
    

    【讨论】:

      【解决方案2】:

      如果您只想获取变量,并拒绝没有任何字符的行,这可能会起作用(data.txt 只是您给出的数据示例生成的 txt):

      fid = fopen('data.txt');
      
      tline = fgets(fid);
      while ischar(tline)
          tmp = cell2mat(regexp(tline,'\=(.*)','match'));
          b=str2double(tmp(2:end));
          if ~isnan(b)
              disp(b)
          end
          tline = fgets(fid);
      end
      
      fclose(fid);
      

      我正在逐行读取txt文件,并使用通用表达式去除无用的字符,然后转换为读取的值的两倍。

      【讨论】:

      • 实际参数名称要复杂得多,例如 pos_rudder_UPR 或 pressure_cylinder_LWR。上面的代码还能用吗?
      • 我编辑了我的答案。对于此输入 A = 1234 B = 1353.335 C = D = 1 pressure_cylinder_LWR = 8 pos_rudder_UPR = p1 = 3 它返回 1234, 1.3533e+003, 1, 8, 3
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-18
      相关资源
      最近更新 更多