For loop Index exceeds the number of array elements.
Mostrar comentarios más antiguos
I am trying to write a script that calculates the limits for any function and then displays the calculations in a 10x2 table. A basic calculus script. It is supposed to list the values as 'x' approaches limit 'a,' from the left and from the right. The script takes two user input in terms of limit 'a' and of a user-defined function 'f(x)'.
I had to use a function handle format for MATLAB to accept functions containing variable 'x' as a string input. And then I used str2func to convert it to be used in a 'for' loop.
Now I'm getting an error saying: Index exceeds the number of array elements. Index must not exceed 1. Error in script (line 29) x = x(k);
How can I make the elements match?
% Script for finding the limits of a f(x) as 'x' approaches 'a'
% first table is from left
% second table is from right
clc
clear
% user inputs
% takes user function as a string and then converts it into a handle function
a = input('Enter limit a = ');
disp(' ')
disp('Type out your function using correct logical operators and parentheses')
disp(' ')
fun = input('Enter the function f(x) = ','s');
fun = "@(x)"+fun;
fun = str2func(fun);
%% Creates array column for x approaching the limit from the LEFT
x = linspace(a-.1,a-.001,10)';
% for loop calculates the limit
% k is an index
% fun(k) and x(k) call the index
for k = 1:10
x = x(k);
fun = fun(k);
end
% display table
T = table(x(:),fun(:))
%% Repeats the sequence for x approaching from the RIGHT
x = linspace(a+.1,a+.001,10)';
for k = 1:10
x=x(k);
fun = fun(k);
end
T = table(x(:),fun(:))
Respuesta aceptada
Más respuestas (1)
KSSV
el 13 de Feb. de 2022
% Script for finding the limits of a f(x) as 'x' approaches 'a'
% first table is from left
% second table is from right
clc
clear
% user inputs
% takes user function as a string and then converts it into a handle function
a = input('Enter limit a = ');
disp(' ')
disp('Type out your function using correct logical operators and parentheses')
disp(' ')
disp('You must put single quotes around your function!')
disp(' ')
fun = input('Enter the function f(x) = ');
fun = "@(x)"+fun;
fun = str2func(fun);
%% Creates array column for x approaching the limit from the LEFT
x = linspace(a-.1,a-.001,10)';
% for loop calculates the limit
% k is an index
% fun(k) and x(k) call the index
% for k = 1:10
% x = x(k);
% fun = fun(k);
% end
y = fun(x) ;
% display table
T = table(x,y)
1 comentario
David Cortes
el 13 de Feb. de 2022
Categorías
Más información sobre Entering Commands en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!