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)
.
So you can simply use the one-liner: data = dlmread('input_file', ' ', 1, 0);
data = load('-ascii','autocleaned. txt'); Loaded the data as wanted in to a matrix in Octave. Since all the data is in fixed width columns (except the last strings), you should be able to read it line by line, using fscanf to decode the line.
A = readmatrix( filename ) creates an array by reading column-oriented data from a file. The readmatrix function performs automatic detection of import parameters for your file. readmatrix determines the file format from the file extension: .
The dimensions of a matrix are the number of rows by the number of columns. If a matrix has a rows and b columns, it is an a×b matrix. For example, the first matrix shown below is a 2×2 matrix; the second one is a 1×4 matrix; and the third one is a 3×3 matrix.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With