Is there anyway that I can have a function and what I must type into the command window in a script?

조회 수: 1 (최근 30일)
I would like to have a function, namely fsolve, and what you must put into the command window to output an answer into one .m file, so everything is inside the .m file, and I do not have to type anything into the command window. I need to have only one .m file as well. Is this possible or must I type things into the command window. I understand that to solve a system of nonlinear equations using fsolve, we must type things into the command window, but is it possible to have these things inside the same .m file as the root2d.m file and to have the program run without anything typed into the command window? I understand this may be not a smart question to ask, but I have not use MATLAB in several months and I am working on an assignment for a professor.
The fsolve and root2d.m file that I am referring to are referenced on this page on the first example
https://www.mathworks.com/help/optim/ug/fsolve.html
Here is my code
function F = root2d(x)
F(1) = 1/sqrt(x(1)) + 2*log10((2.51*0.00001655)/(x(2)*0.267*sqrt(x(1))))
F(2) = 20 - x(1)*(300/0.267)*((x(2))^2/(2*9.81))
end
fun = @root2d;
x0 = [0,0];
x = fsolve(fun,x0)

채택된 답변

Walter Roberson
Walter Roberson 2018년 4월 8일
If you are using R2016b or later you can use
fun = @root2d;
x0 = [0,0];
x = fsolve(fun,x0)
function F = root2d(x)
F(1) = 1/sqrt(x(1)) + 2*log10((2.51*0.00001655)/(x(2)*0.267*sqrt(x(1))))
F(2) = 20 - x(1)*(300/0.267)*((x(2))^2/(2*9.81))
end
all in the same file (but you must use a file name that is not root2d.m )
If you did that then you could click the Run button in the editor to execute the code.
With earlier versions of MATLAB you could do something similar but you would need to use a function, such as
function drive_root
fun = @root2d;
x0 = [0,0];
x = fsolve(fun,x0)
end
function F = root2d(x)
F(1) = 1/sqrt(x(1)) + 2*log10((2.51*0.00001655)/(x(2)*0.267*sqrt(x(1))))
F(2) = 20 - x(1)*(300/0.267)*((x(2))^2/(2*9.81))
end
Both of those could go in the same file, which in this example would be named drive_root.m . You could then run the code by clicking the green Run button in the editor.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Geometry and Mesh에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by