Calling function from another .m file

16 visualizaciones (últimos 30 días)
Joe Ainsworth
Joe Ainsworth el 12 de Sept. de 2021
Comentada: Abolfazl Chaman Motlagh el 12 de Sept. de 2021
Trying to call a function from another file called stringorder.m but getting an error, can someone please explain why.
thank you!
This is the fucntion file
function f = ["Benn" ; "Dan" ; "Lebron" ; "Jim" ; "Rose"];
here is my script
function A = stringorder ;
[M,N]=size(A);
for i = 1:M-1
for j = 1:M-1
curr = A(j);
next = A(j+1);
if upper(curr) > upper(next)
A(j) = next;
A(j+1) = curr;
end
end
end
disp(A);

Respuestas (1)

Abolfazl Chaman Motlagh
Abolfazl Chaman Motlagh el 12 de Sept. de 2021
type this in your script:
function A = stringorder(A)
[M,N]=size(A);
for i = 1:M-1
for j = 1:M-1
curr = A(j);
next = A(j+1);
if upper(curr) > upper(next)
A(j) = next;
A(j+1) = curr;
end
end
end
disp(A);
end
and save it in stringorder.m .
then you have to put the variable in argument of your function:
f = ["Benn" ; "Dan" ; "Lebron" ; "Jim" ; "Rose"];
F_output = stringorder(f)
also you don't have to use disp(A) at end. the output of function will be printed if you don't use ; .
  2 comentarios
Joe Ainsworth
Joe Ainsworth el 12 de Sept. de 2021
@Abolfazl Chaman Motlagh, this didnt work for whatever reason. what do you mean by put the variable in argument of function as in A = stringorder(f)?
its giving men an error on line 4
[M,N]=size(A)
Abolfazl Chaman Motlagh
Abolfazl Chaman Motlagh el 12 de Sept. de 2021
how is this ( [M,N]=size(A) ) in line 4 ? it is in line 2!
you should open a new script. copy the function part of code. save it with same name of function.( here is stringorder) (so the file should be stringorder.m)
then whenever you want to use function, for example in command window of matlab, you have to write name of function and then open parantheses, put your variable and close the parantheses.
% write this on command window :
A = ["Joe" ; "David" ; "Peter"]; % for example
A = stringorder(A)
so you should write second part of code in command window. (or another file which is runnig in same folder with function file.)

Iniciar sesión para comentar.

Categorías

Más información sobre Environment and Settings en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by