Reputation: 121
I am trying to read a matrix from file in Octave but I just can't find a solution. The input file is:
4
1 4 2 3
1 4 2 1
4 2 1 4
1 2 1 3
where 4 is the number of rows and columns. I want to be able to store that information in a matrix and to be able to use it's elements by calling them like a(2,3)
.
Upvotes: 5
Views: 24083
Reputation: 322
just type load + space + file name like
load fileName.txt
data = fileName;
data(2,3)
or
data = load('fileName.txt');
Upvotes: 2
Reputation: 1123
You can use the function dlmread()
:
data = dlmread(file, sep, r0, c0)
Read the matrix data from a text file which uses the delimiter
sep
between data values.If
sep
is not defined the separator between fields is determined from the file itself.Given two scalar arguments
r0
andc0
, these define the starting row and column of the data to be read. These values are indexed from zero, such that the first row corresponds to an index of zero.
So you can simply use the one-liner:
data = dlmread('input_file', ' ', 1, 0);
By calling the function with r0
set to 1
, you're effectively skipping the first line, which contains the (now useless) number of rows.
Upvotes: 6
Reputation: 65430
You should be able to read in all the data using fscanf
. Then you can extract the first value to get the number of rows and columns and then reshape the remainder of the data into the expected size.
fid = fopen('data.dat', 'r');
data = fscanf(fid, '%f');
nRows = data(1);
data = reshape(data(2:end), nRows, nRows).';
%// 1 4 2 3
%// 1 4 2 1
%// 4 2 1 4
%// 1 2 1 3
You can then index into the result just like you would with any array
data(2,3)
%// 2
Upvotes: 1