Array indices must be positive integers or logical values. Error in sym/subsref (line 870)

조회 수: 47 (최근 30일)
I have been having an issue with my code, I am writting a direct method for finding a root from a user input. However, I spent an hour to debug my code with no improvement. A help from the community would be very apperciated.
The error message output is as follow:
Array indices must be positive integers or logical values.
Error in sym/subsref (line 870)
R_tilde = builtin('subsref',L_tilde,Idx);
Error in direct_method (line 21)
fx_value(ii)=fx_given(x(ii))
thank you in advance, my code is as follow:
function Root_Found=direct_method
syms x
fx_given=input('Input the desired function:');
x1=input('Input the lower limit guess value of the root:');
x2=input('Input the upper limit guess value of the root:');
fprintf("The chosen roots values: [x1,x2]=[%.1f,%.1f] \n",x1,x2);
N=input('Input the number of iterations desired:');
x=linspace(x1,x2,N)';
fx_value=zeros(N);
for ii=1:N
fx_value(ii)=fx_given(x(ii))
end
figure
plot(x,fx_value)
title('Direct Method')
xlabel('x')
ylabel('y')
grid on
Root_Found=fx_value;
end

채택된 답변

Walter Roberson
Walter Roberson 2020년 8월 8일
syms x
fx_given=input('Input the desired function:');
We can predict from the error message that whatever the user is entering in response to the prompt is not either an anonymous function or a symbolic function defined with symfun() . For example the user may be entering a formula such as
x^2 + 3*x - sin(x)
Then
fx_value(ii)=fx_given(x(ii))
with fx_given not being a function handle or symbolic function, fx_given(VALUE) would be an attempt to index fx_given at location indicated by VALUE.
If the user is entering a symbolic expression, then you should use matlabFunction to convert the user expression into a function handle, or else you should code as
fx_given(x) = input('Input the desired function:');

추가 답변 (1개)

Image Analyst
Image Analyst 2020년 8월 8일

카테고리

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

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by