Simple read-in to matrix, vector

17 ビュー (過去 30 日間)
poplockandbopit
poplockandbopit 2016 年 8 月 31 日
回答済み: Azzi Abdelmalek 2016 年 8 月 31 日
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 件)

Azzi Abdelmalek
Azzi Abdelmalek 2016 年 8 月 31 日
d=importdata('file.txt')
n=d(1)
M=reshape(d(2:2+n*n-1),n,n)'
v=d(end-n+1:end)

Azzi Abdelmalek
Azzi Abdelmalek 2016 年 8 月 31 日
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)

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by