Undefined function or variable

조회 수: 1 (최근 30일)
Srinivasan Rangan
Srinivasan Rangan 2018년 7월 15일
댓글: Srinivasan Rangan 2018년 7월 15일
Dear All,
I am trying to estimate parameters using non-linear least squares. The version of Matlab I am using is R2018a.
My function is stored in a file myfun.m and has the following lines of code.
function F = myfun(x)
F = (y - (1 + x(1)*(x(2)/0.002))*X1 - (1-x(1)^2)*(x(2)/x(3))*X2 - x(4)*X3)
My dataset is a matrix read in as column vectors which includes the column vectors y, X1,X2, and X3 are stored in a file in a data file.
Both the data file and the file containing the code are in this directory: 'D:\Users\Srinivasan Rangan'
When I type pwd, the above directory is displayed as the current directory.
Before estimating the function, I open the dataset and I see all the variables of the dataset under the workspace panel on the right hand side of the screen.
However, when I try to estimate the parameters of the function using
x = lsqnonlin(myfun,x0)
I get the following error message:
undefined function or variable 'y'.
Error in myfun (line 2)
F = (y - (1 + x(1)*(x(2)/0.002))*X1 - (1-x(1)^2)*(x(2)/x(3))*X2 - x(4)*X3)
I do see y as loaded in the right hand panel under workspace.
How can I fix this error and perform my estimation?
Thanks, Srinivasan

채택된 답변

Guillaume
Guillaume 2018년 7월 15일
Function can't see the variables in your main workspace. You have to pass any variable you want to use to the function.
Change your function to:
function F = myfun(x, y, X)
F = (y - (1 + x(1)*(x(2)/0.002))*X(:,1) - (1-x(1)^2)*(x(2)/x(3))*X(:, 2) - x(4)*X(:,3));
end
Then change the lsqnonlin call to:
X = [X1, X2, X3]; %numbered variables are bad. Use arrays instead
x = lsqnonlin(@(x) myfun(x, y, X), x0);
A better name than X would be better. One that has meaning.
  댓글 수: 1
Srinivasan Rangan
Srinivasan Rangan 2018년 7월 15일
Thanks so much! This worked very well and I am getting estimates

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

추가 답변 (1개)

Walter Roberson
Walter Roberson 2018년 7월 15일
y exists in your base workspace, but not in the workspace of your function.
You can either pass y to the function as a parameter, or you can define myfun as an anonymous function after you load y.
https://www.mathworks.com/help/matlab/math/parameterizing-functions.html

카테고리

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

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by