Can I save multiple seperate functions to one .m file?

357 vues (au cours des 30 derniers jours)
Philip Brewer
Philip Brewer le 15 Fév 2018
Commenté : Walter Roberson le 2 Fév 2023
I see that when I write a function that it can only be named the same as the .m file name, is there any way that I can change that so that I can call on the function by a different name? I want to do this so that I can put two different functions in one file. For example I have to functions and I want them to be:
function mult(a,b)
c=a*b
end
function div(a*b)
d=a/b
end
I want to call on these functions at separate times, not run them together, can I have them both in the same file?
  7 commentaires
Philip Brewer
Philip Brewer le 15 Fév 2018
Thanks, this is what I was trying to do
function ideal(R)
n=2;
V=1;
P=100:10:400;
igl=(P*V)/(n*R);
T=table(P', igl');
T.Properties.VariableNames = {'Pressure_Bar' 'Ideal_temp_K'}
end
function waals(R,a,b)
n=2;
V=1;
P=100:10:400;
E1=P+(n^2*a/V^2);
E2=V-n*b;
E3=E1*E2;
E4=n*R;
vdw=E3/E4;
T=table(P', vdw');
T.Properties.VariableNames = {'Pressure_Bar' 'Waal_temp_K'}
end
But from what I am seeing, both of these functions would need to be in separate files.
Walter Roberson
Walter Roberson le 15 Fév 2018
Those would need to be in separate files.
You should probably be returning T from the function.

Connectez-vous pour commenter.

Réponses (4)

per isakson
per isakson le 28 Jan 2020
Modifié(e) : per isakson le 2 Fév 2023
IMO: The best solutions is a class with static methods.
>> lib.div( 8, 2 )
ans =
4
>> lib.mult( 8, 2 )
ans =
16
where
classdef lib
methods ( Static = true )
function c = mult(a,b)
c=a*b;
end
function d = div(a,b)
d=a/b;
end
end
end
  3 commentaires
RAHUL JAISWAL
RAHUL JAISWAL le 1 Nov 2020
if i want to call any of the above functon/
per isakson
per isakson le 1 Nov 2020
There are examples of calls at the top of the answer

Connectez-vous pour commenter.


Walter Roberson
Walter Roberson le 15 Fév 2018
No. Only the first function in a .m file can be invoked by name, and the name it is known by to be called is the same as the name of the .m file rather than the actual function name (but modern versions will give you a warning if those are not the same.)
If you need to be able to invoke a different function, then the outside world has to somehow be given a handle to the function. For example,
function funs = switchyard
funs.mult = @mult;
funs.div = @div;
end
function c = mult(a, b)
c = a*b;
end
function d = div(a, b)
d = a/b;
end
then it would be legal for something to call
F = switchyard();
F.div( F.mult(3, 7), 19)
The closest that there is to an exception to this is class definitions, which you to create object-oriented objects and put several implementing functions into the same .m file.
You should probably also have a look at "packages" . And at "private" directories.
  2 commentaires
Stephen23
Stephen23 le 15 Fév 2018
Just to emphasize that while it is certainly possible to pass handles and use them, in most cases it would be easier to keep the Mfiles simple and use a private directory, or to write class.
Walter Roberson
Walter Roberson le 15 Fév 2018
switchyards were not uncommon in earlier MATLAB when objects were implemented as struct (struct are still fairly important to objects under the hood but the implementation is significantly different now.)
The Instrument Control toolbox effectively constructs the kind of struct I show, holding pointers to the implementing functions for the interface associated with the object being constructed.

Connectez-vous pour commenter.


Sidra  Ashraf
Sidra Ashraf le 28 Jan 2020
addpath([functiondir 'AAM Functions'])
addpath([functiondir 'Functions'])
AAM Functions and Functions both are files in which multiple functions are existing.
now the question is that where these should be placed in the same directory or separete??
  1 commentaire
Walter Roberson
Walter Roberson le 28 Jan 2020
Are those files or are they directories? addpath() can only be used with directories. If they are directories then MATLAB is able to find code in either of them when they are both on the path, so use two or use a combined one depending on the software engineering needs. (Methods defined in private directories can only be called from the parent directory, so if you had functions in AAM Functions that needed to call something in Functions/private then you would need to combine the directories.)

Connectez-vous pour commenter.


Victor Manuel
Victor Manuel le 2 Fév 2023
Modifié(e) : per isakson le 2 Fév 2023
I see that when I write a function that it can only be named the same as the .m file name, is there any way that I can change that so that I can call on the function by a different name? I want to do this so that I can put two different functions in one file. For example I have to functions and I want them to be:
%%%% A 99 LINE TOPOLOGY OPTIMIZATION CODE BY OLESIGMUND, OCTOBER 1999 %%%
function toppl(nelx,nely,volfrac,penal,rmin);
% INITIALIZE
x(1:nely,1:nelx) = volfrac;
loop = 0;
change = 1.;
% START ITERATION
while change > 0.01
loop = loop + 1;
xold = x;
% FE-ANALYSIS
[U]=FE(nelx,nely,x,penal);
% OBJECTIVE FUNCTION AND SENSITIVITY ANALYSIS
[KE] = lk;
c = 0.;
for ely = 1:nely
for elx = 1:nelx
n1 = (nely+1)*(elx-1)+ely;
n2 = (nely+1)* elx +ely;
Ue = U([2*n1-1;2*n1; 2*n2-1;2*n2; 2*n2+1;2*n2+2; 2*n1+1;2*n1+2],1);
c = c + x(ely,elx)^penal*Ue'*KE*Ue;
dc(ely,elx) = -penal*x(ely,elx)^(penal-1)*Ue'*KE*Ue;
end
end
% FILTERING OF SENSITIVITIES
[dc] = check(nelx,nely,rmin,x,dc);
% DESIGN UPDATE BY THE OPTIMALITY CRITERIA METHOD
[x] = OC(nelx,nely,x,volfrac,dc);
% PRINT RESULTS
change = max(max(abs(x-xold)));
disp([' It.: ' sprintf('%4i',loop) ' Obj.: ' sprintf('%10.4f',c) ...
' Vol.: ' sprintf('%6.3f',sum(sum(x))/(nelx*nely)) ...
' ch.: ' sprintf('%6.3f',change )])
% PLOT DENSITIES
colormap(gray); imagesc(-x); axis equal; axis tight; axis off;pause(1e-6);
end
%%%%%%%%%% OPTIMALITY CRITERIA UPDATE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [xnew]=OC(nelx,nely,x,volfrac,dc)
l1 = 0; l2 = 100000; move = 0.2;
while (l2-l1 > 1e-4)
lmid = 0.5*(l2+l1);
xnew = max(0.001,max(x-move,min(1.,min(x+move,x.*sqrt(-dc./lmid)))));
if sum(sum(xnew)) - volfrac*nelx*nely > 0;
l1 = lmid;
else
l2 = lmid;
end
end
%%%%%%%%%% MESH-INDEPENDENCY FILTER %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [dcn]=check(nelx,nely,rmin,x,dc)
dcn=zeros(nely,nelx);
for i = 1:nelx
for j = 1:nely
sum=0.0;
for k = max(i-floor(rmin),1):min(i+floor(rmin),nelx)
for l = max(j-floor(rmin),1):min(j+floor(rmin),nely)
fac = rmin-sqrt((i-k)^2+(j-l)^2);
sum = sum+max(0,fac);
dcn(j,i) = dcn(j,i) + max(0,fac)*x(l,k)*dc(l,k);
end
end
dcn(j,i) = dcn(j,i)/(x(j,i)*sum);
end
end
%%%%%%%%%% FE-ANALYSIS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [U]=FE(nelx,nely,x,penal)
[KE] = lk;
K = sparse(2*(nelx+1)*(nely+1), 2*(nelx+1)*(nely+1));
F = sparse(2*(nely+1)*(nelx+1),1); U = zeros(2*(nely+1)*(nelx+1),1);
for elx = 1:nelx
for ely = 1:nely
n1 = (nely+1)*(elx-1)+ely;
n2 = (nely+1)* elx +ely;
edof = [2*n1-1; 2*n1; 2*n2-1; 2*n2; 2*n2+1; 2*n2+2; 2*n1+1; 2*n1+2];
K(edof,edof) = K(edof,edof) + x(ely,elx)^penal*KE;
end
end
% DEFINE LOADS AND SUPPORTS (HALF MBB-BEAM)
F(2,1) = -1;
fixeddofs = union([1:2:2*(nely+1)],[2*(nelx+1)*(nely+1)]);
alldofs = [1:2*(nely+1)*(nelx+1)];
freedofs = setdiff(alldofs,fixeddofs);
% SOLVING
U(freedofs,:) = K(freedofs,freedofs) \ F(freedofs,:);
U(fixeddofs,:)= 0;
%%%%%%%%%% ELEMENT STIFFNESS MATRIX %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [KE]=lk
E = 1.;
nu = 0.3;
k=[ 1/2-nu/6 1/8+nu/8 -1/4-nu/12 -1/8+3*nu/8 ...
-1/4+nu/12 -1/8-nu/8 nu/6 1/8-3*nu/8];
KE = E/(1-nu^2)*[ k(1) k(2) k(3) k(4) k(5) k(6) k(7) k(8)
k(2) k(1) k(8) k(7) k(6) k(5) k(4) k(3)
k(3) k(8) k(1) k(6) k(7) k(4) k(5) k(2)
k(4) k(7) k(6) k(1) k(8) k(3) k(2) k(5)
k(5) k(6) k(7) k(8) k(1) k(2) k(3) k(4)
k(6) k(5) k(4) k(3) k(2) k(1) k(8) k(7)
k(7) k(4) k(5) k(2) k(3) k(8) k(1) k(6)
k(8) k(3) k(2) k(5) k(4) k(7) k(6) k(1)];
function top (nelx,nely,volfrac,penal,rmin);
Error: Function definition are not supported in this context. Functions can only be created as local or nested functions in code files.
  2 commentaires
per isakson
per isakson le 2 Fév 2023
Is there any way that I can change that so that I can call on the function by a different name? Answer: NO.
btw: It's good practice to end function definitions with the keyword end
Walter Roberson
Walter Roberson le 2 Fév 2023
I see that when I write a function that it can only be named the same as the .m file name
That is not exactly correct.
When you have a .m or .mlx that starts with function then the name of the first function given in the file is overridden by the name of the file. So if you were to (for example) copy tf.m to my_tf.m then even without changing the contents of my_tf.m you would be able to call upon my_tf() . The situation is as-if you had changed the function line . So if you had code in the file that invoked the function by its function name then it would not find the version in that file.
function f = factorial(n)
if n <= 0
f = 1;
else
f = n*factorial(n-1);
end
end
if you were to store that as my_factorial.m then you could invoke my_factorial(7) but when the code encounted the recursive reference to factorial it would not know that the code was referring to the same file, just as if what you had written was
function f = my_factorial(n)
if n <= 0
f = 1;
else
f = n*factorial(n-1);
end
end
None of this helps you directly call upon more than one function stored in the same file.
If you need to invoke more than one function stored in the same file, then there are several options, including creating a class that has static methods with the various names; once the class is loaded, those names all become visible.
There are other ways, such as
function [init_fcn, read_fcn] = get_drivers(devicename)
init_fcn = @init_z80;
read_fcn = @read_z80;
function varargout = init_z80(varargin)
stuff
end
function varargout = read_z80(varargin)
more stuff
end
end
The return from this get_drivers would be handles of functions that are stored inside get_drivers.m . The calling code would store them and invoke the approrpiate one at need.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Data Type Identification dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by