【问题标题】:how to read a matrix from a text file in matlabmatlab如何从文本文件中读取矩阵
【发布时间】:2013-04-02 21:46:47
【问题描述】:

我有一个包含数字(整数)值的 500 columns500 rows 的文本文件。行中的每个元素都由制表符分隔。我想将此文件作为matlab 中的矩阵读取。示例(我的文本文件是这样的):

 1 2 2 1 1 2 
 0 0 0 1 2 0
 1 2 2 1 1 2 
 0 0 0 1 2 0

在 matlab 中将此文本文件作为矩阵 (a[]) 读取后,我想做transpose。 帮帮我。

【问题讨论】:

标签: matlab transpose


【解决方案1】:

您可以使用importdata。 比如:

filename = 'myfile01.txt';
delimiterIn = '\t';
headerlinesIn = 1;
A = importdata(filename,delimiterIn,headerlinesIn);
A_trans = A';

如果您的文件没有任何 haeder,您可以跳过标题行。(这是实际数据开始之前的行数)

取自 Matlab 文档,improtdata

【讨论】:

    【解决方案2】:

    您是否厌倦了load-ascii 选项?
    例如

     a = load('myfile.txt', '-ascii'); % read the data
     a = a.'; %' transpose
    

    【讨论】:

      【解决方案3】:
      % Pre-allocate matrix
      Nrow=500; Ncol=500;
      a = zeros(Nrow,Ncol);
      % Read file
      fid = fopen('yourfile.txt','r');
      for i:1:Nrow
         a(i,:) = cell2mat(textscan(fid,repmat('%d ',Ncol));
      end
      fclose(fid); 
      % Trasnspose matrix
      a_trans = a.';
      

      【讨论】:

        【解决方案4】:

        你可以这样做:

        yourVariable = importdata('yourFile.txt')';
        %Loads data from file, transposes it and stores it into 'yourVariable'.
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-06-23
          • 2015-06-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多