使用Matlab在函数内加载数据文件

时间:2013-09-07 11:24:36

标签: matlab function file loaddata

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

1 个答案:

答案 0 :(得分: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;