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

37 views (last 30 days)
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

Accepted Answer

Walter Roberson
Walter Roberson on 8 Aug 2020
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:');

More Answers (1)

Image Analyst
Image Analyst on 8 Aug 2020

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!