If function, Index exceeds matrix dimensions.
6 ビュー (過去 30 日間)
古いコメントを表示
Hi All, my code is:
syms x y m n;
funt=@(x,m,n,y) (100-10-x+y).^(-0.5)-(2.*n+4.*m.*y);
if funt(x,m,n,0)<=0
funfun(x,m,n)=0;
elseif funt(x,m,n,50)>=0
funfun(x,m,n)=50;
else funfun(x,m,n)=fzero(@(y) (100-10-x+y).^(-0.5)-(2.*n+4.*m.*y),[0,50]);
end
feval(funfun,10,0.002,0.4)
The error is:
Conversion to logical from sym is not possible.
I would like to construct a function of x and z. z can be regarded as an input and the range of x is [0,50]. Then I test this function at the value of 10 and z=[0.002,0.4]. This is my first time to use if function in matlab. So it might be some errors in my code. Thank you so much in advance. Any help is appreciated!
2 件のコメント
Star Strider
2019 年 2 月 5 日
The error is:
Index exceeds matrix dimensions.
This is most likely because ‘funfun’ does not exist until you define it here (as a matrix, not a function).
What what is ‘funfun’, and do you want to do with ‘funfun’?
採用された回答
Adam Danz
2019 年 2 月 5 日
編集済み: Adam Danz
2019 年 2 月 5 日
When evaluating your anonymous function, the error is caused by "z(2)". In your code, size(z) = [1, 1] and you're trying to index the 2nd value; hence, "Index exceeds matrix dimensions".
funt=@(x,y,z) (100-10-x+y).^(-0.5)-(2.*z(2)+4.*z(1).*y);
% **** error
If z is always [0.002, 0.4] then you can replace z(1) and z(2) with those values in the anonymous function. If the value of z changes, then you'll need to provide those inputs when you call the function. But currently, your symbolic 'z' is does not have 2 elements.
3 件のコメント
Adam Danz
2019 年 2 月 5 日
編集済み: Adam Danz
2019 年 2 月 5 日
In your 3rd line, if you evaluate the anonymous function like so (below), it produces a symbolic expression.
funt(x,0,m,n)
ans =
1/(90 - x)^(1/2) - 2*n % <-- symbolic !
You're then entering that symbolic expression in to feval(). The first input to feval() needs to be a function handle, or a string / character vector to a function. When you enter a symbolic expression, feval() fails and throws an error.
It's not clear to me what you're doing so I'm not sure what adivice to give. If you have values for x, m, and n, then avoid the call to syms() at the beginning and skip the call to feval().
if funt(x,0,m,n) <= 0 %instead of if feval(funt()) <=0
Lastly, there's nothing wrong with indexing within your anonymous function. You just need to make sure the input variables have a sufficient number of elements so your indices don't cause an error. In your case, 'z' was a symbol of size [1,1] and you were trying to index the 2nd position.
その他の回答 (1 件)
Walter Roberson
2019 年 2 月 6 日
You need to switch to using piecewise()
Note that if you matlabFunction an expression involving piecewise then you must specify the 'File' option and what you get out will not be vectorized with respect to that variable .
0 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!