【问题标题】:How to make a .m file read an input csv file passed as a parameter?如何使 .m 文件读取作为参数传递的输入 csv 文件?
【发布时间】:2022-12-16 17:00:21
【问题描述】:

我是 Matlab 的新手,在制作 .m 文件时遇到困难读取我作为参数从命令提示符传递的输入 csv 文件。我知道必须编写一个函数来读取输入文件作为参数。这是我在 .m 文件中编写的用于接受输入文件的代码:

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

我希望作为参数传递的文件名由函数“csvread”读取并将其保存在 D 中。我正在使用以下命令来执行脚本:

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

我能够在没有任何错误的情况下执行脚本,但它没有读取输入文件,因为如果下游分析能够读取文件并对其执行某些功能,它应该已经保存了一个新文件。

谁能建议如何读取我的 matlab 脚本中的输入文件以及要传递的正确命令?

【问题讨论】:

  • 为什么它应该保存一个新文件?为什么函数的输出参数 data 没有在函数内部使用?您的函数被定义为不返回任何内容。您可能希望将 data 重命名为 D,反之亦然。
  • 如果您只是在交互式 MATLAB 会话中运行它,您可以通过以 nodesktop 方式分层来运行代码,从而使它过于复杂,您可以调试并查看发生了什么。当您满意时,您可以返回从 cmd 运行它
  • 我将尝试使用交互式 MATLAB 会话来调试它。谢谢@Wolfie!我仍在学习 MATLAB,但我会尝试你的建议@Sardar Usama。谢谢!

标签: linux matlab user-input


【解决方案1】:

尝试使用此功能。注意不要使用预订的名称:

读取数据.m

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

为了测试,您可以直接在命令窗口和编辑编辑器,这是大多数功能,大部分时间,测试的地方,直到您对您的处理完全满意为止。

>> data=readdat(filename);

查看数据,您可以了解文件是否按应有的方式读取。

>> data(:,1)

您可以继续运行其他脚本,例如matlab_filename.m。但最好的选择是拥有一个适用于一切的功能:

处理数据.m

function data=processdat(filename)
% Original Function
addpath(genpath('./matlab_and_R_scripts'));
tic;
data=csvread(filename,1,1);
toc;
% Paste in here all the matlab_filename.m code, or do a call:
matlab_filename;
% Do not uncomment this exit in here, since you want to keep working until the function do what you need
% exit;

以后,如果你想要一些严肃的自动化并希望某些编程任务在某个时间表下重复您的代码,您当然可以安排一个 Windows bat 命令,在这种情况下,您可以取消注释 processdat.m 末尾的 exit; 终止符。

进程数据.bat

 matlab -nodisplay -nosplash -nodesktop -r processdat

记得确保操作系统可以访问软件,并且 Matlab 可以访问处理数据.如有疑问,请放置正确的路径:

进程数据.bat

 cprogramsinmatlab -nodisplay -nosplash -nodesktop -r cilesprocessdat.m

【讨论】:

  • 谢谢@Brethlosze。这真的帮助我解决了我的问题。
【解决方案2】:

我通过从@Brethlosze 的回答中获得一些见解来解决问题。这是我在我的中传递输入参数所做的我的脚本.m脚本:

  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

我使用以下命令从命令行执行脚本:

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

input_file 是“example.csv”,output_file 是“example.mat”。

【讨论】:

    猜你喜欢
    • 2020-04-04
    • 2021-03-14
    • 2020-05-17
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多