MATLAB Answers

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

95 views (last 30 days)
Svenja Illemann
Svenja Illemann on 29 Jun 2021
Commented: Steven Lord on 2 Jul 2021
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
Stephen
Stephen on 30 Jun 2021
"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)

per isakson
per isakson on 29 Jun 2021
Edited: per isakson on 29 Jun 2021
"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
Steven Lord
Steven Lord on 2 Jul 2021
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.

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!