Problem

Consider this comma-separated data file: data.in. Write a simple script named csv2formatted that takes two input arguments representing the input and output file names. Then, the script writes the same input float data to the output file data.out in a formatted style, like this example output file: example output file. Note that every numer in the output file has only three significant digits after the decimal point.

MATLAB

Write your MATLAB script as a function that takes the input and output file names as input arguments to a function named csv2formatted, so that it can be called like the following from the MATLAB command line.

csv2formatted('data.in','data.matlab.out')
Python

Write your Python script in such a way that it takes the input and output file names from the Bash command line arguments, like the following,

python csv2formatted.py data.in data.python.out

Solution

MATLAB

Here is an example implementation in MATLAB.

function  csv2formatted(inputFileName,outputFileName)
    d = csvread(inputFileName);
    fileID = fopen(outputFileName,'w');
    for irow = 1:length(d(:,1))
        fprintf(fileID,'%14.3f',d(irow,:));
        fprintf(fileID,'\n');
    end
    fclose(fileID);
end
Python

Here is an example implementation in Python.

import sys
outfile = open(sys.argv[2], 'w')
with open(sys.argv[1], 'r') as infile:
    for row in infile:
        for column in row.split(','):
            outfile.write( '{:14.3f}'.format(float(column)) )
        outfile.write('\n')
    outfile.close()

Comments