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 CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by