how to read a matrix from a text file in matlab

对着背影说爱祢 提交于 2019-12-01 08:15:50

问题


I have a text file which has 500 columns and 500 rows, of numerical(integer) values . Every element in the row is separated by a tab. I want to read this file as a matrix in matlab. Example(my text file is like this):

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

And after reading this text file as a matrix (a[]) in matlab I want to do transpose. Help me.


回答1:


You can use importdata. Something like:

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

You can skip headerlines if your file does not have any haeder.. (It is the number of lines before the actual data starts)

Taken from Matlab documentation, improtdata




回答2:


Have you tired load with -ascii option?
For example

 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:


You could simply do:

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


来源:https://stackoverflow.com/questions/15762503/how-to-read-a-matrix-from-a-text-file-in-matlab

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!