Load data files within a function using Matlab

1.2k views Asked by At

I have created two .m files in order to read data files using the importdata command. Now I need to put these values in a function. How can I do this?

1

There are 1 answers

0
Tom S On

I'm not sure whether you want to do subsequent operations (function calls) with the data from within your *.m file script (assuming it's a script), or whether you want to be able to use these data import scripts from within some other function.

If the former, it's pretty straightforward. Assuming your *.m file looks something like this...

% 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);

...then passing that data to a function is trivial, e.g. plot(dataOfInterest)

On the other hand, perhaps you want to be able to use this data import process within some other function. Two ways of doing that. One would be to just call the script, assuming the path to the data you want is never going to change (doubtful!). Better way is to turn your *.m file script (here, getDataScript) into a function itself, which returns your data of interest.

function dataOfInterest = getDataFunction(myFile)

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

Now you can call this from with another function...

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;