【问题标题】:Load data files within a function using Matlab使用 Matlab 在函数中加载数据文件
【发布时间】:2013-09-11 10:34:53
【问题描述】:

我创建了两个 .m 文件,以便使用 importdata 命令读取数据文件。现在我需要将这些值放入一个函数中。我怎样才能做到这一点?

【问题讨论】:

  • 第一个 data=myDataProvider()myDataConsumer(data)

标签: matlab function file loaddata


【解决方案1】:

我不确定您是否想对 *.m 文件脚本(假设它是一个脚本)中的数据执行后续操作(函数调用),或者您是否希望能够使用这些数据导入脚本来自其他函数。

如果是前者,那就很简单了。假设您的 *.m 文件看起来像这样......

% getDataScript.m file for getting some data...

myFile = 'C:\myFolder\myFile.txt';
newImport = importdata(myFile);
numericData = newImport.data;

% Perhaps we only want the third column of a 2D matrix
dataOfInterest = numericData(:, 3);

...然后将该数据传递给函数是微不足道的,例如plot(dataOfInterest)

另一方面,也许您希望能够在其他功能中使用此数据导入过程。有两种方法。一种是只调用脚本,假设您想要的数据的路径永远不会改变(值得怀疑!)。更好的方法是把你的 *.m 文件脚本(这里是 getDataScript)变成一个函数本身,它会返回你感兴趣的数据。

function dataOfInterest = getDataFunction(myFile)

newData = importdata(myFile);
numericData = newData.data;
dataOfInterest = numericData(:, 3);

现在您可以使用另一个函数调用它...

function myCalculation = doFancyMath(myFile)

% First get the data you want to work with
workingData = getDataFunction(myFile);

% Now do whatever you need to do with it
myCalculation = workingData.^2;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-12
    • 1970-01-01
    • 1970-01-01
    • 2013-08-19
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    • 2021-05-31
    相关资源
    最近更新 更多