Simple read-in to matrix, vector

20 visualizzazioni (ultimi 30 giorni)
poplockandbopit
poplockandbopit il 31 Ago 2016
Risposto: Azzi Abdelmalek il 31 Ago 2016
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.

Risposte (2)

Azzi Abdelmalek
Azzi Abdelmalek il 31 Ago 2016
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 il 31 Ago 2016
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)

Categorie

Scopri di più su Data Type Conversion in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by