how to write functions in an m-file?

조회 수: 150 (최근 30일)
learner
learner 2015년 7월 16일
답변: Image Analyst 2015년 7월 16일
If I define a function like
function (cost) = objective (time)
cost = some non linear equation in time
It shows error in line-1 input argument that is at '(time)'. Please help me how to write a function?
Also, if my function depends on two variables say t1 and t2, how to define it? I've tried using
function (cost) = objective (t1 t2)
and also tried this:
time = [t1 t2]
function (cost) = objective (time)
But it shows error.
  댓글 수: 3
learner
learner 2015년 7월 16일
편집: Walter Roberson 2015년 7월 16일
Thanks GopalKrishnan, but it's typo in my question. earlier I've tried
function [ f ] = fun1(x)
x=[2 3 4]
And it worked fine for me but in other file, I've written:
function [ cost ] = objective( time )
time=[t1 T]
Also I tried
function [ cost ] = objective( t1 T )
Or
function [ cost ] = objective( t )
t=[t1 T]
But every time it showed an error. I am unable to identify, what went wrong.
Please help.
Walter Roberson
Walter Roberson 2015년 7월 16일
Please copy the entire text of the error message.

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

답변 (3개)

chef13
chef13 2015년 7월 16일
You should write something like that:
function [ cost ] = objective( time )
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
% Here you put what your function does
end
I hope it helps you.

Ellison Castro
Ellison Castro 2015년 7월 16일
I think it should be constructed like this:
function[output1, output2, ...] = function_name(input1, input2, ...)
% Insert your main code here using your inputs and returning outputs.
end;
You should also remove this line of code if you're using it at the beginning.
clear; clc; clf;
The first line of the m-file must be the function syntax. To call the function, create another m-file using this syntax:
[variable1, variable2, ...] = function_name(value1, value2, ...)
Your number of inputs should be equal to your specified inputs on your function's m-file.
  댓글 수: 1
chef13
chef13 2015년 7월 16일
편집: chef13 2015년 7월 16일
Don't put the semicolomn after the end , it is not needed.

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


Image Analyst
Image Analyst 2015년 7월 16일
time is a built-in function. Use another name for it, like myTimes.

카테고리

Help CenterFile Exchange에서 Introduction to Installation and Licensing에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by