How to correct "Function definitions are not permitted at the prompt or in scripts"
Matlab expects functions to be in their own file. Copy the above code to a file 'stat.m' and it should work.
This policy does cause an unnecessary number of short files, but it is required because of the way matlab handles variable scope. Each file gets its own scope, and all variables in the command prompt have global scope.
As Quantum7 pointed out, you have defined the function in the same script, which will give you an error. Regardless of whether the function is in a different file or not, what you've written there is not a valid operation with symbolic variables. If you simply comment out the second line and run it, you'll get the following error:
??? Error using ==> sym.sym>checkindex at 2697
Index must be a positive integer or logical.
which is because i-1
is zero for the first loop, and MATLAB starts counting at 1. If you try for i=2:3
, the you get this error,
??? Error using ==> mupadmex
Error in MuPAD command: Index exceeds matrix dimensions.
because the symbolic variable is just a 1x1
array.
From what you've written, it seems like you have an array T1
, and T2
is constructed from T1
according to the relation: T2(i)=T1(i)+2*[T1(i-1)+T1(i+1)]
. I think a better way to do what you're trying is to use anonymous functions.
I'll slightly change the indexing to account for the fact that at the first and last element, you'll get an error because the index will exceed T1
's bounds. Nevertheless, the answer is the same.
dummyT1=[0;T1(:);0];
f=@(i)(dummyT1(i+1)+2*(dummyT1(i)+dummyT1(i+2)));
T2=f(1:3)
If you don't want to add zeros, but instead make it circular (i.e., T1(0)=T1(3)
), then you can use the same code by easily modifying the definition of f
.