Hope this will work
close all;
clear;
clc;
syms a b g(a,b) %Changes
g = output(a,b);
function out = output(a,b)
for i = 1:10
p(i) = i^2+a*b;
if i==1
q(i) = str2sym(num2str(2));%Changes
else
q(i)= p(i-1);
end
end
out = sum(p.*q);
end
%output
%g =
%2*a*b + (a*b + 1)*(a*b + 4) + (a*b + 4)*(a*b + 9) + (a*b + 9)*(a*b + 16) + (a*b + 16)*(a*b + 25) + (a*b + 25)*(a*b + 36) + (a*b + 36)*(a*b + 49) + (a*b + 49)*(a*b + 64) + (a*b + 64)*(a*b + 81) + (a*b + 81)*(a*b + 100) + 2;