Javascript required
Skip to content Skip to sidebar Skip to footer

How to Read and Write Out of a Text File in Matlab

Creating Functions

Overview

Educational activity: 45 min
Exercises: 20 min

Questions

  • How can I teach MATLAB how to do new things?

Objectives

  • Compare and dissimilarity MATLAB function files with MATLAB scripts.

  • Define a function that takes arguments.

  • Test a role.

  • Recognize why we should separate programs into minor, unmarried-purpose functions.

If nosotros just had one data set to analyze, it would probably exist faster to load the file into a spreadsheet and employ that to plot some simple statistics. Simply we have twelve files to cheque, and may have more in future. In this lesson, nosotros'll learn how to write a function so that we can repeat several operations with a single command.

Permit's start by defining a function fahr_to_kelvin that converts temperatures from Fahrenheit to Kelvin:

                          function              ktemp              =              fahr_to_kelvin              (              ftemp              )              %FAHR_TO_KELVIN   Convert Fahrenheit to Kelvin              ktemp              =              ((              ftemp              -              32              )              *              (              v              /              9              ))              +              273.15              ;              end                      

A MATLAB function must be saved in a text file with a .m extension. The proper noun of that file must exist the same as the function defined within it. The name must starting time with a letter and cannot contain spaces. And so, you will need to salve the above code in a file called fahr_to_kelvin.grand. Remember to save your one thousand-files in the electric current directory.

The first line of our function is called the function definition, and it declares that we're writing a function named fahr_to_kelvin, that has a single input parameter,ftemp, and a single output parameter, ktemp. Anything post-obit the function definition line is called the body of the part. The keyword stop marks the end of the function body, and the function won't know about any lawmaking after finish.

function-definition

A function tin can have multiple input and output parameters if required, only isn't required to accept any of either. The general form of a function is shown in the pseudo-code below:

                          function              [              out1              ,              out2              ]              =              function_name              (              in1              ,              in2              )              %FUNCTION_NAME   Function clarification              % This department below is called the trunk of the function              out1              =              something              calculated              ;              out2              =              something              else              ;              cease                      

Only as nosotros saw with scripts, functions must be visible to MATLAB, i.e., a file containing a function has to be placed in a directory that MATLAB knows nigh. The almost convenient of those directories is the electric current working directory.

GNU Octave

In mutual with MATLAB, Octave searches the current working directory and the path for functions called from the command line.

We tin can call our function from the control line similar any other MATLAB function:

When nosotros pass a value, similar 32, to the function, the value is assigned to the variable ftemp so that it can be used inside the office. If we desire to return a value from the function, we must assign that value to a variable named ktemp—in the first line of our part, nosotros promised that the output of our part would be named ktemp.

Outside of the function, the variables ftemp and ktemp aren't visible; they are merely used by the role torso to refer to the input and output values.

This is one of the major differences betwixt scripts and functions: a script can exist thought of every bit automating the command line, with total access to all variables in the base workspace, whereas a office can but read and write variables from the calling workspace if they are passed as arguments — i.due east. a function has its ain separate workspace.

Now that we've seen how to convert Fahrenheit to Kelvin, information technology'due south like shooting fish in a barrel to convert Kelvin to Celsius.

                          function              ctemp              =              kelvin_to_celsius              (              ktemp              )              %KELVIN_TO_CELSIUS   Convert from Kelvin to Celcius              ctemp              =              ktemp              -              273.15              ;              end                      

Over again, we can phone call this function like any other:

                          >>              kelvin_to_celsius              (              0.0              )                      

What about converting Fahrenheit to Celsius? We could write out the formula, but we don't need to. Instead, we can compose the two functions we take already created:

                          role              ctemp              =              fahr_to_celsius              (              ftemp              )              %FAHR_TO_CELSIUS   Convert Fahrenheit to Celcius              ktemp              =              fahr_to_kelvin              (              ftemp              );              ctemp              =              kelvin_to_celsius              (              ktemp              );              terminate                      

Calling this office,

nosotros get, every bit expected:

This is our first gustatory modality of how larger programs are built: we ascertain bones operations, then combine them in ever-larger chunks to go the issue we want. Existent-life functions volition usually be larger than the ones shown here—typically half a dozen to a few dozen lines—but they shouldn't always be much longer than that, or the next person who reads information technology won't be able to sympathise what's going on.

Concatenating in a Function

In MATLAB, nosotros concatenate strings by putting them into an array or using the strcat role:

                              >>                disp                ([                'abra'                ,                'cad'                ,                'abra'                ])                          
                              >>                disp                (                strcat                (                'a'                ,                'b'                ))                          

Write a function called debate that has two parameters, original and wrapper and adds wrapper before and after original:

                              >>                disp                (                fence                (                'name'                ,                '*'                ))                          

Solution

                                  function                  wrapped                  =                  fence                  (                  original                  ,                  wrapper                  )                  %Argue   Render original string, with wrapper prepended and appended                  wrapped                  =                  strcat                  (                  wrapper                  ,                  original                  ,                  wrapper                  );                  end                              

Getting the Outside

If the variable south refers to a string, then s(1) is the string's start graphic symbol and s(finish) is its concluding. Write a function chosen outer that returns a cord fabricated up of only the first and final characters of its input:

Solution

                                  function                  ends                  =                  outer                  (                  s                  )                  %OUTER   Render start and final characters from a string                  ends                  =                  strcat                  (                  s                  (                  1                  ),                  s                  (                  stop                  ));                  end                              

Variables Inside and Outside Functions

Consider our function fahr_to_kelvin from before in the episode:

                              part                ktemp                =                fahr_to_kelvin                (                ftemp                )                %FAHR_TO_KELVIN   Convert Fahrenheit to Kelvin                ktemp                =                ((                ftemp                -                32                )                *                (                5.0                /                ix.0                ))                +                273.15                ;                stop                          

What does the following code brandish when run — and why?

                              ftemp                =                0                ktemp                =                0                disp                (                fahr_to_kelvin                (                8                ))                disp                (                fahr_to_kelvin                (                41                ))                disp                (                fahr_to_kelvin                (                32                ))                disp                (                ktemp                )                          

Solution

                259.8167 278.1500 273.1500 0                              

ktemp is 0 because the function fahr_to_kelvin has no knowledge of the variable ktemp which exists outside of the function.

In one case we start putting things in functions then that nosotros can re-apply them, nosotros need to starting time testing that those functions are working correctly. To see how to do this, let'southward write a office to center a dataset around a particular value:

                          function              out              =              centre              (              information              ,              desired              )              out              =              (              information              -              mean              (              data              (:)))              +              desired              ;              cease                      

Nosotros could test this on our bodily data, just since nosotros don't know what the values ought to be, it will be hard to tell if the upshot was correct, Instead, let'southward create a matrix of 0's, and then center that around 3:

                          >>              z              =              zeros              (              2              ,              two              );              >>              centre              (              z              ,              three              )                      

That looks right, so let'south try out center function on our real data:

                          >>              information              =              readmatrix              (              'data/inflammation-01.csv'              );              >>              centered              =              center              (              information              (:),              0              )                      

It's hard to tell from the default output whether the outcome is correct–this is oftentimes the case when working with fairly large arrays–simply, in that location are a few elementary tests that volition reassure us.

Let'due south summate some unproblematic statistics:

                          >>              disp              ([              min              (              data              (:)),              mean              (              data              (:)),              max              (              information              (:))])                      

And let'due south practice the same after applying our heart function to the information:

                          >>              disp              ([              min              (              centered              (:)),              mean              (              centered              (:)),              max              (              centered              (:))])                      

That seems almost correct: the original mean was about half dozen.i, so the lower bound from cipher is now about -half dozen.one. The mean of the centered data isn't quite zilch–we'll explore why not in the challenges–but it's pretty shut. Nosotros can even go farther and check that the standard deviation hasn't inverse:

                          >>              std              (              data              (:))              -              std              (              centered              (:))                      

The departure is very small. It's nevertheless possible that our office is incorrect, but information technology seems unlikely enough that we should probably get back to doing our analysis. We have ane more than task outset, though: we should write some documentation for our function to remind ourselves later what information technology'south for and how to use it.

                          office              out              =              center              (              information              ,              desired              )              %Middle   Eye data around a desired value.              %              %       center(Information, DESIRED)              %              %   Returns a new assortment containing the values in              %   Information centered around the value.              out              =              (              information              -              mean              (              data              (:)))              +              desired              ;              cease                      

Annotate lines immediately below the function definition line are chosen "assist text". Typing help function_name brings up the help text for that function:

            Center   Centre data effectually a desired value.      center(Information, DESIRED)  Returns a new array containing the values in Data centered around the value.                      

Testing a Function

  1. Write a function chosen normalise that takes an assortment as input and returns an array of the same shape with its values scaled to prevarication in the range 0.0 to i.0. (If L and H are the everyman and highest values in the input array, respectively, then the function should map a value v to (five - L)/(H - L).) Be sure to give the function a comment block explaining its apply.

  2. Run help linspace to run into how to use linspace to generate regularly-spaced values. Use arrays like this to exam your normalise function.

Solution

  1.                                           function                      out                      =                      normalise                      (                      in                      )                      %NORMALISE   Return original array, normalised so that the                      %            new values lie in the range 0 to ane.                      H                      =                      max                      (                      max                      (                      in                      ));                      50                      =                      min                      (                      min                      (                      in                      ));                      out                      =                      (                      in                      -                      L                      )/(                      H                      -                      L                      );                      end                                      
  2.                                           a                      =                      linspace                      (                      1                      ,                      10                      );                      % Create evenly-spaced vector                      norm_a                      =                      normalise                      (                      a                      );                      % Normalise vector                      plot                      (                      a                      ,                      norm_a                      )                      % Visually check normalisation                                      

Convert a script into a role

Write a role called plot_dataset which plots the three summary graphs (max, min, std) for a given inflammation data file.

The role should operate on a unmarried data file, and should have two parameters: file_name and plot_switch. When called, the function should create the iii graphs produced in the previous lesson. Whether they are displayed or saved to the results directory should be controlled past the value of plot_switch i.e. plot_dataset('data/inflammation-01.csv', 0) should display the corresponding graphs for the first data prepare; plot_dataset('data/inflammation-02.csv', ane) should relieve the figures for the second dataset to the results directory.

You should more often than not be reusing code from the plot_all script.

Be sure to give your part help text.

Solution

                                  part                  plot_dataset                  (                  file_name                  ,                  plot_switch                  )                  %PLOT_DATASET    Perform analysis for named data file.                  %   Create figures to show average, max and min inflammation.                  %   Brandish plots in GUI using plot_switch = 0,                  %   or save to disk using plot_switch = 1.                  %                  %   Example:                  %       plot_dataset('data/inflammation-01.csv', 0)                  % Generate string for image name:                  img_name                  =                  replace                  (                  file_name                  ,                  '.csv'                  ,                  '.png'                  );                  img_name                  =                  supervene upon                  (                  img_name                  ,                  'data'                  ,                  'results'                  );                  patient_data                  =                  readmatrix                  (                  file_name                  );                  if                  plot_switch                  ==                  i                  effigy                  (                  'visible'                  ,                  'off'                  )                  else                  figure                  (                  'visible'                  ,                  'on'                  )                  end                  subplot                  (                  2                  ,                  2                  ,                  i                  )                  plot                  (                  mean                  (                  patient_data                  ,                  i                  ))                  ylabel                  (                  'boilerplate'                  )                  subplot                  (                  2                  ,                  2                  ,                  2                  )                  plot                  (                  max                  (                  patient_data                  ,                  [],                  1                  ))                  ylabel                  (                  'max'                  )                  subplot                  (                  ii                  ,                  ii                  ,                  3                  )                  plot                  (                  min                  (                  patient_data                  ,                  [],                  ane                  ))                  ylabel                  (                  'min'                  )                  if                  plot_switch                  ==                  1                  impress                  (                  img_name                  ,                  '-dpng'                  )                  close                  ()                  end                  end                              

Automate the assay for all files

Modify the plot_all script so that every bit it loops over the information files, it calls the office plot_dataset for each file in plough. Your script should save the prototype files to the 'results' directory rather than displaying the figures in the MATLAB GUI.

Solution

                                  %PLOT_ALL    Analyse all inflammation datasets                  %   Create figures to prove average, max and min inflammation.                  %   Relieve figures to 'results' directory.                  files                  =                  dir                  (                  'data/inflammation-*.csv'                  );                  for                  i                  =                  ane                  :                  length                  (                  files                  )                  file_name                  =                  files                  (                  i                  )                  .                  name                  ;                  file_name                  =                  fullfile                  (                  'data'                  ,                  file_name                  );                  % Process each data prepare, saving figures to disk.                  plot_dataset                  (                  file_name                  ,                  i                  );                  end                              

We have now solved our original problem: we tin analyze any number of data files with a single command. More importantly, we accept met two of the most important ideas in programming:

  1. Use arrays to store related values, and loops to repeat operations on them.

  2. Utilise functions to make code easier to re-use and easier to understand.

Key Points

  • Intermission programs up into brusque, single-purpose functions with meaningful names.

  • Ascertain functions using the role keyword.

faithfulyeatcheed.blogspot.com

Source: https://swcarpentry.github.io/matlab-novice-inflammation/07-func/index.html