Simple read-in to matrix, vector

I need to write a script that will open a file, read in an integer n, then a matrix of size n x n, then a vector of size n x 1. So for n = 2, there might be a data file (say 'dat.dat1') with first line 2, then 2 lines each with 2 integers, then 2 lines each with 1 integer. But the program needs to work for different positive integers n.
This is what I've tried so far:
fid = fopen('dat.dat1');
n = fgetl(fid);
A = fgetl(fid);
for ii = 1:n-1
A = [A; sscanf(fgetl(fid),'%f')'];
end
b = fgetl(fid);
for jj = 1:n-1
b = [b; sscanf(fgetl(fid),'%f')'];
end
fclose(fid);
But this doesn't seem to work. When I try it out I get an error that says: "Error using vertcat. Dimensions of matrices being concatenated are not consistent."
Any ideas? Also, how could I refactor my code to take the filename as a parameter?
Thanks.

回答(2 个)

d=importdata('file.txt')
n=d(1)
M=reshape(d(2:2+n*n-1),n,n)'
v=d(end-n+1:end)
If you want to use your code, you have to know that fgetl load the line as a string, you need to convert it to double
fid = fopen('fic.txt');
n = str2num(fgetl(fid))
A = str2num(fgetl(fid))
for ii = 1:n-1
A = [A; sscanf(fgetl(fid),'%f')']
end
b = str2num(fgetl(fid));
for jj = 1:n-1
b = [b; sscanf(fgetl(fid),'%f')']
end
fclose(fid)

类别

帮助中心File Exchange 中查找有关 Data Import and Export 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by