Is it possible to put multiple functions in one matlab file file?

Hi everyone.
I would like to combine several matlab files .m into one .m file.
All .m files consist of a "function main" that reads a .nc file:
My problem now is that I have a .nc file for each of 6 scenarios (for example PRE2005) and I would like to run all 6 scenarios simultaneously in Matlab. In other words, I currently have six seperate scripts. Is there a way to make a single script out of it, which then runs 6 loops and spits out 6 graphics?
I'm really not that talented in Matlab.
Can someone help me?
function main
clear all;
close all;
clc;
% -------parameter ---------
file_name = 'PRE2005_result.nc';
time_point = 120; %month
level = 1; %surface temperature
% ---------------------------
% ========= putting some routines to the Matlab search path ===============
AAA_set_path_func
% =========================================================================
% ===== monthly mean over 10 years ===================
for time_point = 1:120
% -------- read the lon and lat coordinates -----
lon_plus = read_data_from_ncfile(file_name,'lon',-1);
lat = read_data_from_ncfile(file_name,'lat',-1);
% -----------------------------------------------
% ----- read the temperature ts from file ---------
temp_s = read_data_from_ncfile(file_name,'ts',time_point,-1,-1);
temp_s = temp_s - 273.15; % Transform to C
[lon,temp_s_neg] = trafo_lon_field_plusminus_func(lon_plus,temp_s);
% ----------------------------------------------
% ========= testing the projections ===========================
figure(1);
m_proj('robinson','lon',[min(lon) max(lon)],'lat',[min(lat) max(lat)],'rec','off')
m_pcolor(lon,lat,temp_s_neg); shading('interp'); colorbar; title(colorbar,'Temperatur °C');
caxis([-30 50]);
m_coast('color','k');
m_grid('tickdir','out','linewidth',1,'XaxisLocation','bottom','xtick',[-120 -60 0 60 120],'ytick',[-90 - 60 -45 -30 0 30 45 60 90]);
title({'Globale Oberflächentemperatur';'Szenario PRE2005'});
CT = cbrewer('seq', 'YlOrRd', 100)
colormap (CT)
% =============================================================
end
return

3 Comments

It would help immeasurably for us (and you, too) if you would format your code by indenting for..end loops, etc., etc., ... I'll let you keep whatever decoration you like, but to my eye all the lines and so on just distract from the code more than they clarify anything.
The answer to the Q?, though, is to turn this function into one that accepts a filename as input argument, and then call it from the main loop -- the ideal way to get the list of files is probably to use a wildcard pattern and then dir().
One additional stylistic note --
function main
clear all;
close all;
clc;
...
Take all these out of the function -- they're rarely needed at all and definitely not nice to have your functions blowing away stuff you may have worked hard to have created in the command space before you began the function.
Functions have their own context so the clear doesn't do anything anyways for variables, etc., because there aren't any until the function creates them.
As for the "all" keyword, see the note at the documentation--
"Calling clear all decreases code performance, and is usually unnecessary. For more information, see the Tips section."
Hi dpb. Thanks for your advice. The script was set up this way by my lecturer at the university and this is how we are supposed to keep the "outline" so he can better understand it. However, he could not give me an answer to my question, because he himself is not perfectly familiar with Matlab. Nevertheless, I take note of your advice. Thank you a lot.
Unfortunately, since I'm not that familiar with the commands in Matlab, I don't really understand what you mean by wildcard pattern and dir(). Does wildcard pattern mean that you name the files in a similar structure and then Matlab knows which file to refer to next? And does dir() mean that Matlab just takes all the files that match the dir() command?
However, then I still don't know how that helps me run multiple main functions in Matlab simultaneously.
Thanks.
"The script was set up this way by my lecturer at the university and this is how we are supposed to keep the "outline" so he can better understand it."
A good "outline" does not use CLEAR ALL, CLOSE ALL, nor CLC.
A good "outline" does require consistent code indentation to make the code easier to understand.
"I don't really understand what you mean by wildcard pattern and dir()."
No one expects you to know everything... even experienced MATLAB users on this forum do not know everything. But if something is not clear, you should first look in the documentation yourself.
If the DIR command is not clear to you, did you look in the DIR documenation?
"Does wildcard pattern mean that you name the files in a similar structure and then Matlab knows which file to refer to next? And does dir() mean that Matlab just takes all the files that match the dir() command? "
As the DIR documentation explains, DIR returns a list of filenames that match the given pattern (the pattern may includes wildcard chracters, which match any characters in the filename. Note that this is not particular to MATLAB, this is a very very common command used in many programming languages and OSs).
You can easily iterate over that list of filenames:

Sign in to comment.

Answers (1)

"I currently have six seperate scripts [you mean functions?]" What differs between the six functions? The name of the nc-files and the title of the plots differ, but what more? Is the year in "PRE2005" the only thing that varies?
There are two (possible more) approaches:
  1. Convert the six functions (without clear all) to six local functions (in the same file as the main function).
  2. Convert the six functions (without clear all) to one parameterized local function.
six local functions. The main function contains six lines
function main()
foo1()
foo2()
foo3()
foo4()
foo5()
foo6()
end
function foo1()
...
end
function foo2()
...
end
% et cetera
end
one parameterized local function.

5 Comments

Hi per isakson. Thanks for your answer. Regarding your question what differs between the functions. You are right. It only differs the file_name (.nc) and the plot names. My six file_names are named
  1. PRE2005_result.nc
  2. RCP2.6_result.nc
  3. RCP4.5_result.nc
  4. RCP6.0_result.nc
  5. RCP8.5_result.nc
  6. RCP8.5_II_result.nc
I tried to implement it according to your example, but after the first function has run through I get an error message saying "Unrecognized function or variable 'foo2'.". Did I miss something?
Svenja
"Did I miss something?"
Did you define a local function and call it by whatever function name that you gave it?
Of course your functions should be named something more self-explanatory than FOO1, etc.
As per isakson wrote, most likely you should just have one function rather than six separated functions.
Hi. I did it like this:
function main()
PRE()
RCP1()
RCP2()
RCP3()
RCP4()
RCP5()
RCP6()
end
function PRE()
...
end
function RCP1()
...
end
function RCP2()
...
end
function RCP3()
...
end
function RCP4()
...
end
function RCP5()
...
end
function RCP6()
...
end
end
Every function contains now my former fFUNCTION MAIN which you can see in my original question above.
Did you try to run main() ?
What is PRE() supposed to do? ( main() contains seven calls in total.)
Regarding the name, foo, see Wikipedia
Stephen's comment on calling and defining functions is clarifying.
Every function contains now my former fFUNCTION MAIN which you can see in my original question above.
That's not very maintainable. If you find a bug in one of those functions you will need to fix it in each of those functions, and by Murphy's Law eventually you'll fix a bug in all but one of those functions and then have to figure out what's going wrong with that one function that "ought" to be the same as the others.
Consider two example functions at the end of this comment. Both the functions add1 and add2 add 3 to a set of data.
y1 = add1
y1 = 1×10
4 5 6 7 8 9 10 11 12 13
y2 = add2
y2 = 1×10
13 23 33 43 53 63 73 83 93 103
But if I ever want to change the data, I need to go in and modify add1 and/or add2. If I want to make them add 4 to the data instead, I need to modify both add1 and add2.
However if I separate the data from the program like with function add3 (again at the end of this comment)
x3 = 1:10;
y3 = add3(x3)
y3 = 1×10
4 5 6 7 8 9 10 11 12 13
x4 = 10:10:100;
y4 = add3(x4)
y4 = 1×10
13 23 33 43 53 63 73 83 93 103
then to change the data I don't need to touch add3 at all. I need to change the lines above that define x3 and x4. If I need to make the function add 4 to the data instead, I don't need to touch x3 and x4. I just need to change one function, add3, and then running the four lines that define x3, y3, x4, and y4 would give me updated results.
You've written your code like add1 and add2. Instead I recommend using add3 as a model. Treat your filenames more like data not code.
function y = add1
x = 1:10;
y = x + 3;
end
function y = add2
x = 10:10:100;
y = x + 3;
end
function y = add3(x)
y = x + 3;
end

Sign in to comment.

Categories

Products

Release

R2020a

Asked:

on 29 Jun 2021

Commented:

on 2 Jul 2021

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!