Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

# I want to convert my program in to a function......tried function but something is wrong....???

조회 수: 2 (최근 30일)
Maruti Patil 2015년 9월 13일
마감: MATLAB Answer Bot 2021년 8월 20일
Here is my program. How to write its function??
Inputs and output are as indicated in program
clc
clear all
close all
%=======================Inputs to the program==============================
f = @(x) x.^2+54/x;
k=1;
x(k)=1;
a=x(k);
e=0.1;
%============================Main program=================================
if abs(x(k))>0.01
dx=0.01*abs((x(k)));
else
dx=0.0001;
end
for m=1:inf
D1=(f(a+dx)-f(a-dx))/(2*dx);
D2=(f(a+dx)-2*f(a)+f(a-dx))/(dx)^2;
x(k+1)=a-(D1/D2);
a=x(k+1); % Program Output after m iterations
C1=(f(a+dx)-f(a-dx))/(2*dx);
if abs(C1)<e
break
else
k=k+1;
end
end
%================================END=======================================
%===========Progrm output is the final value of 'a'========================

### 답변 (2개)

Walter Roberson 2015년 9월 13일
f=inline(eqn);
However, you have
a=x(k);
and other references to x(k) when you have no x defined.
##### 댓글 수: 0이전 댓글 -2개 표시이전 댓글 -2개 숨기기

Image Analyst 2015년 9월 13일
You need two function lines if you're going to put this in one m-file. One for the test program, and one for your function:
function TestMyFunction()
clc
clear all
close all
%=======================Inputs to the program==============================
f = @(x) x.^2+54/x;
k=1;
x(k)=1;
a=x(k);
e=0.1;
% Now have TestMyFunction() call MyFunction()
new_a = MyFunction(f,k,x,a,e);
function a = MyFunction(f,k,x,a,e)
% Code for it....
Again, that can be all in one m-file, or you can use two separate m-files if you want.
##### 댓글 수: 1이전 댓글 -1개 표시이전 댓글 -1개 숨기기
Maruti Patil 2015년 9월 13일
편집: Walter Roberson 2015년 9월 13일
I want in the function in the following format,(i.e i want to directly specify values and it should show final value of 'a'
[a] = MyFunction('x.^2+54/x',1,1,0.1)
for this I coded in the following format
function [a] = MyFunction(eqn,k,a,e)
a=x(k);
f=inline('eqn');
if abs(x(k))>0.01
dx=0.01*abs((x(k)));
else
dx=0.0001;
end
for m=1:inf
D1=(f(a+dx)-f(a-dx))/(2*dx);
D2=(f(a+dx)-2*f(a)+f(a-dx))/(dx)^2;
x(k+1)=a-(D1/D2);
a=x(k+1); % Program Output after m iterations
C1=(f(a+dx)-f(a-dx))/(2*dx);
if abs(C1)<e
break
else
k=k+1;
end
end
Please tell me where i am doing mistake

이 질문은 마감되었습니다.

### Community Treasure Hunt

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

Start Hunting!

Translated by