Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a matrix from a txt file in Rust?

Tags:

file

matrix

rust

File example; square matrix; size of matrix after #

#3
1.1 -0.2 0.1
0.1 -1.2 -0.2
0.2 -0.1 1.1

Approximately so i would write it in C

double **A;
int i,j,size=0;
FILE *f=NULL;

f=fopen("input.txt","w");
fscanf(f,"#%d\n",&size);
A=(double**)malloc(size*sizeof(double*));
for(i=0;i<size;i++)
    A[i]=(double*)malloc(size*sizeof(double));

for(i=0;i<size;i++)
{
    for(j=0;j<size;j++)
    {
        fscanf(f,"%lf",&A[i][j]);
    }
}
fclose(f);

I tried to use the method "read_to_string" and parse String, but I'm confused by the conversion between String and str.

like image 451
vessd Avatar asked Apr 11 '15 17:04

vessd


1 Answers

This is a naive translation of your code to Rust:

use std::fs::File;
use std::io::{BufRead, BufReader};

fn main() {
    // open the file
    let mut f = BufReader::new(File::open("input.txt").unwrap());

    // read the first line and extract the number from it
    let mut num_line = String::new();
    f.read_line(&mut num_line).unwrap();
    let n: usize = num_line[1..].trim().parse().unwrap();

    // preallocate the array and read the data into it
    let mut arr = vec![vec![0f64; n]; n];
    for (i, line) in f.lines().enumerate() {
        for (j, number) in line.unwrap().split(char::is_whitespace).enumerate() {
            arr[i][j] = number.trim().parse().unwrap();
        }
    }

    println!("{:?}", arr);
}

There is more idiomatic way to perform the loop in Rust, though:

use std::fs::File;
use std::io::{BufRead, BufReader};

fn main() {
    let mut f = BufReader::new(File::open("input.txt").unwrap());

    let mut num_line = String::new();
    f.read_line(&mut num_line).unwrap();
    let n: usize = num_line[1..].trim().parse().unwrap();

    let arr: Vec<Vec<f64>> = f.lines()
        .take(n)
        .map(|l| l.unwrap().split(char::is_whitespace)
             .take(n)
             .map(|number| number.parse().unwrap())
             .collect())
        .collect();

    println!("{:?}", arr);
}

In fact, you don't even need the number of lines in advance to read the data if the format of your file is completely fixed:

use std::fs::File;
use std::io::{BufRead, BufReader};

fn main() {
    let mut f = BufReader::new(File::open("input.txt").unwrap());

    let mut s = String::new();
    f.read_line(&mut s).unwrap();

    let arr: Vec<Vec<f64>> = f.lines()
        .map(|l| l.unwrap().split(char::is_whitespace)
             .map(|number| number.parse().unwrap())
             .collect())
        .collect();

    println!("{:?}", arr);
}
like image 178
Vladimir Matveev Avatar answered Oct 17 '22 14:10

Vladimir Matveev