I need help with an error in my symsum code
    3 views (last 30 days)
  
       Show older comments
    
So I make this code (for a trapezoid numeric integration). But I keep getting the same error no matter what I do. Can anyone tell me where my mistake is and how to fix it? Thanks beforehand. MATLAB Code:
a=-3.4;
b=2.1; 
fun=inline('(x^2)*sin(x)-exp(-2*x)');
for m=2:2:50 
    h=(b-a)/m;
    x=a:h:b;
    for l=1:m+1
        y(l)=fun(x(l));
    end
    k=sym('k');
    s2=symsum(h/2*(y(k)+y(k+1)),k,1,m); 
end
The Error:
Error using sym/subsindex (line 737) Invalid indexing or function definition. When defining a function, ensure that the arguments are symbolic variables and the body http://de.mathworks.com/matlabcentral/answers/questions/new/?s_tid=gn_mlc_ans_ask#code  of the function is a SYM expression. When indexing, the input must be numeric, logical, or ':'.
0 Comments
Answers (1)
  Abhishek
 on 5 Mar 2025
        Hi, 
It seems like you're encountering an issue with symbolic indexing in MATLAB. I tried this in MATLAB R2024b, and I faced the same issue.  
The error arises because the code attempts to use symbolic variables for indexing numeric arrays, which is not supported. In MATLAB, array indices must be numeric, logical, or the colon operator (:), and symbolic variables can’t be used for indexing numeric arrays. This is a common pitfall when working with symbolic math alongside numeric operations.  
For more details, you can refer to the MATLAB documentation on symbolic math: https://www.mathworks.com/help/releases/R2024b/symbolic/index.html 
As a workaround, you can use the following code: 
a = -3.4; 
b = 2.1; 
fun = @(x) (x.^2).*sin(x) - exp(-2.*x); 
for m = 2:2:50 
    h = (b-a)/m; 
    x = a:h:b; 
    y = fun(x); 
    % Trapezoidal rule calculation 
    s2 = h/2 * (y(1) + 2*sum(y(2:end-1)) + y(end)); 
    % Display the result for each m 
    fprintf('m = %d, Integral approximation = %.5f\n', m, s2); 
end 
Hope this solves the issue.
0 Comments
See Also
Categories
				Find more on Calculus in Help Center and File Exchange
			
	Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
