Simple read-in to matrix, vector

42 views (last 30 days)
poplockandbopit on 31 Aug 2016
Answered: Azzi Abdelmalek on 31 Aug 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')'];
b = fgetl(fid);
for jj = 1:n-1
b = [b; sscanf(fgetl(fid),'%f')'];
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?

Answers (2)

Azzi Abdelmalek
Azzi Abdelmalek on 31 Aug 2016

Azzi Abdelmalek
Azzi Abdelmalek on 31 Aug 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')']
b = str2num(fgetl(fid));
for jj = 1:n-1
b = [b; sscanf(fgetl(fid),'%f')']

Community Treasure Hunt

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

Start Hunting!

Translated by