Scilab allows the user to read matrix data from external text files. This feature is useful when, for example, we want to import some numerical table data from an external source (e.g. LibreOffice Calc).
Data can be read using the read()
embedded Scilab function:
where:
y
– is the variable which will store the content of the file to be read
i
– is a scalar which specifies how many lines from the file should be read
j
– is a scalar which specifies how many columns from the file should be read
If the file to be read is located in the current Scilab working folder, only the name and extension needs to be specified, as a string. We can also specify the full path of the file, for example:
'C:\My Documents\fileName.txt'
(Windows)'home/user/Documents/fileName.txt'
(Linux)
As an example, we will create a text file in which we enter a 3 x 3 matrix. We save the file in the current Scilab working directory with the name and extension 'dataFile.txt'
.
In order to read the content and assign it to a variable y
, we enter the following instructions in the Scilab console:
-->y=read('dataFile.txt',3,3)
y =
1. 2. 3.
4. 5. 6.
7. 8. 9.
-->
As you can see, the content of the file is read and the values are assigned to the variable y
.
If we don’t know the numbers of rows we want to read, we can use -1
as number of rows. In this case, Scilab will scan the entire file and read all the lines.
-->y=read('dataFile.txt',-1,3)
y =
1. 2. 3.
4. 5. 6.
7. 8. 9.
-->
If we specify, as column size, the total number of elements of the file, the data will be read as a vector instead of a matrix:
-->y=read('dataFile.txt',-1,9)
y =
1. 2. 3. 4. 5. 6. 7. 8. 9.
-->
In order to write matrix data to an external file, we can use the write()
embedded Scilab function.
The syntax of the write()
function is simpler, we only need to specify:
- the file name and extension or the full path, name and extension (as a string)
- the Scilab variable to be save in the file
For example, we define a Scilab matrix variable x
as:
-->x = [11 22 33;44 55 66;77 88 99]
x =
11. 22. 33.
44. 55. 66.
77. 88. 99.
-->
In order to save it in an external file (dataFileWrite.txt
), we need to enter in the Scilab console the following instructions:
-->write('dataFileWrite.txt',x)
-->
We can check if the data was saved correctly by opening the newly created text file:
Further, we can read back the data in Scilab and assign it to the y
variable:
-->y=read('dataFileWrite.txt',-1,3)
y =
11. 22. 33.
44. 55. 66.
77. 88. 99.
-->
For any questions, observations and queries regarding this article, use the comment form below.
Don’t forget to Like, Share and Subscribe!
Bob
Every time I try to read a text file, scilab tells me that either the file does not exist, or that read permission is denied. What is going on and how do I fix it?