如何从matlab中的文本文件中读取矩阵

时间:2013-04-02 11:04:56

标签: matlab transpose

我有一个文本文件,其中包含数字(整数)值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。 帮助我。

4 个答案:

答案 0 :(得分:2)

您可以使用importdata。 类似的东西:

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

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

取自Matlab文档,improtdata

答案 1 :(得分:1)

您是否因load选项而感到疲惫-ascii? 例如

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

答案 2 :(得分:0)

% 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.';

答案 3 :(得分:0)

你可以这样做:

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