Calling function from another .m file
32 次查看(过去 30 天)
显示 更早的评论
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);
0 个评论
回答(1 个)
Abolfazl Chaman Motlagh
2021-9-12
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 个评论
Abolfazl Chaman Motlagh
2021-9-12
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.)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!