Calling a function in MATLAB

조회 수: 1,284 (최근 30일)
user06
user06 2015년 2월 23일
댓글: Walter Roberson 2024년 1월 19일
How can I call a function written in an .m file?

채택된 답변

Stephen23
Stephen23 2015년 2월 23일
편집: MathWorks Support Team 2019년 5월 22일
To call a function or a script, just write its name with the necessary inputs:
my_function(...)
Or
my_script
This works in the command window, or within another function or script.
You might like to revise the differences between scripts and functions in MATLAB, as these have very different properties! You also have to ensure that the called function can be found by MATLAB, which means it must be on the search path .
  댓글 수: 2
user06
user06 2015년 2월 23일
actually i have written a function in a diff file ok now i need to call that function from a different file. then how to do that?
Stephen23
Stephen23 2015년 2월 23일
Your two functions are in two different Mfiles. If these are functions you should ensure that the function and Mfile names are the same. Then you can simply call one function from the other one (assuming that they are both on the MATLAB search path). If this is one function:
function y = my_square(x)
% square a number
y = x.^2;
end
then we can simply call it in another function like this:
function out = my_fun
a = 3;
out = my_square(a); % <- call the other function
end

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Aicha Ibtissem
Aicha Ibtissem 2024년 1월 19일
편집: Walter Roberson 2024년 1월 19일
Hello, I cant call my function, I have this error.THANKS
Error<<Execution of script myplotfunction1 as a function is not supported:
C:\Users\fadel\Documents\MATLAB\myplotfunction1.m>>
clear all;
clc;
function myplotfunction(equation)
x=linspace(-10,10,100);
y=eval(equation);
figure;
plot(x,y,'lineWidth',2)
title(['Représentation graphique de la fonction : ' equation]);
xlabel('x');
ylabel('y');
grid on;
end
  댓글 수: 2
Steven Lord
Steven Lord 2024년 1월 19일
Delete these two lines from your file. They make your file a script file, not a function file, and you can't call a script with input arguments like you call a function.
clear all;
clc;
Walter Roberson
Walter Roberson 2024년 1월 19일
The
clear all
clc;
makes that into a script. Get rid of those.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Functions에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by