MATLAB: Unexpected error: Undefined function or variable

error

I have a matlab code
function ElementStiffness
global element_no;
global n_dof;
global p;
for s=1:n_dof
for t=1:n_dof
k(s,t)=0;
end
end
no_gp=NumberOfGaussPoints;
for i=1:no_gp
all_gauss_pts_wts=GaussPtsWts(no_gp);
gauss_pt=all_gauss_pts_wts(i,1);
gauss_wt=all_gauss_pts_wts(i,2);
for s=1:n_dof
for t=1:n_dof
dN=LagrangianShapeFnsDerivatives(gauss_pt);
k(s,t)=k(s,t)+(dN(s,1)*dN(t,1)*A(element_no)*E(element_no)*(1/J));
end
end
end
end
function [dN]=LagrangianShapeFnsDerivatives(gp)
global p;
term1=0;
for i=1:p+1
zi(i)=-1+((2/p)*(i-1));
prodDen=1;
sum=0;
for j=1:p+1
zi(j)=-1+((2/p)*(j-1));
if(j~=1)
sum=sum+zi(j);
prodDen=prodDen*(zi(i)-zi(j));
end
end
I get an errors
>> LagrangianShapeFnsDerivatives(gp)
Undefined function or variable 'gp'.*

Best Answer

You cannot run your LagrangianShapeFnsDerivatives by using the Run menu item or the F5 key while you are in the routine at the editor. If you want to run it by itself, you need to go to the command line and type
LagrangianShapeFnsDerivatives(173.9)
or something similar -- that is, you need to pass a value in to the routine to be worked on there under the name "gp"
You can go to the ElementStiffness routine in the editor and use the Run menu item or F5 key there to start that routine, because that routine does not use any input arguments. Or you could go to the command line and type
ElementStiffness
there, and that would run that routine. ElementStiffness will ideally call LagrangianShapeFnsDerivatives with an appropriate argument.
Caution:
  1. never use "sum" as the name of a variable: that clashes with the use of "sum" as a very commonly use MATLAB routine. A routine that you could, incidentally, be using to make your code shorter.
  2. In the code shown you never give a value to the global variable "p" or "n_dof" or "element_no". If you try to run your routines without having assigned values to those global variables, you will definitely run into problems.
  3. In the code shown you give no definition for NumberOfGaussPoints, GaussPtsWts, A, E, J. If those are not the names of .m files or of "function" in a section of code you have not shown us, ElementStiffness will fail.
  4. You define your routine LagrangianShapeFnsDerivatives as returning a value in the variable dN, but you never assign a value to dN. You do assign a value to "sum" and to "prodDen" but you never use those after the loop.
  5. hint:
j = 1 : p;
zj = sum(-1+((2/p)*(j-1)); %not the variable "sum", the MATLAB routine "sum"
prodDen = prod(diff(zj)); %loop Ma, no loop!