Search code examples
linuxmatlabuser-input

How to make a .m file read an input csv file passed as a parameter?


I am new in Matlab and facing difficulty in making a .m file read the input csv file that I am passing as an argument from the command prompt. I understand that a function has to be written to read the input file as a parameter. Here is the code I wrote inside the .m file to accept the input file:

function data=input(filename);
addpath(genpath('./matlab_and_R_scripts'));
tic
D=csvread(filename,1,1);

I want the filename passed as an argument to be read by the function "csvread" and save it in D. I am using the following command to execute the script:

matlab -nodisplay -nosplash -nodesktop -r "input 'exp2_1_DMatrix.csv';run('matlab_filename.m');exit;"

I am able to execute the script without any errors but it is not reading the input file as the downstream analysis should have saved a new file if it was able to read the file and execute some functions on it.

Can anyone please suggest how to read the input file in my matlab script and the proper command to pass?


Solution

  • I solved the problem by gaining some insight from @Brethlosze's answer. If you want to avoid a local function then function shouldn't have a name but start with an []. Here is what I did to pass an input argument in my myScript.m script:

      function [] = myScript(input_file, output_file)
        addpath(genpath('../matlab_and_R_scripts'));
        tic
        D=csvread(input_file,1,1);
        % Some code operations
        save(output_file,'save_what_you_want')
        toc
      end
    

    And I executed the script from command line using the following command:

    matlab -nodisplay -nosplash -nodesktop -r "myScript 'example.csv' 'example.mat'"
    

    The input_file is 'example.csv' and output_file is 'example.mat'.