How to fix "Function definitions not allowed in tooltip or scripts"

I want to write the code for this equation: T2(i)=T1(i)+2*[T1(i-1)+T1(i+1)]

 syms T1 T2 function [T2] = stat(T1) for i=1:3 T2(i)=T1(i)*2+[T1(i-1,)+T1(i+1,)]*2 end 

I want to create the code T2(111)=T1(111)+2*[T1(011)+T(211)] , and the cycle will continue. but matlab gives this error

"Function definitions are not allowed in the prompt or in scripts

How can I solve this problem?

+4
source share
4 answers

Matlab expects functions to be in their own file. Copy the above code into the stat.m file and it should work.

This policy causes an unnecessary number of short files, but this is necessary because the matlab method handles the variable scope. Each file gets its own scope, and all the variables on the command line have a global scope.

+4
source

As stated in Quantum7, you defined the function in the same script, which will give you an error. Regardless of whether the function is in another file or not, what you wrote there is not a valid operation with symbolic variables. If you just comment out the second line and run it, you will get the following error:

??? Error using ==> sym.sym> checkindex in 2697

The index must be a positive integer or logical.

because i-1 is zero for the first cycle, and MATLAB starts counting from 1. If you try for i=2:3 , you get this error,

??? Error using ==> mupadmex

Error in MuPAD command: index exceeds matrix size.

because the symbolic variable is just a 1x1 array.

From what you wrote, it seems that you have an array of T1 , and T2 built from T1 in accordance with the relation: T2(i)=T1(i)+2*[T1(i-1)+T1(i+1)] . I think the best way to do what you are trying to use anonymous functions.

I’ll change the indexing on the account a bit so that you get an error in the first and last element, because the index will exceed the T1 border. However, 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 do not want to add zeros, but instead make it circular (i.e. T1(0)=T1(3) ), then you can use the same code, easily changing the definition of f .

+2
source

I think this is a simple problem that I solve to press the play button in the editor file, that is, compile your function in the Matlab command window, and then describe your inputs and give the function parameters ...

0
source

Functions in scripts allowed from R2016 or later

https://www.mathworks.com/help/matlab/matlab_prog/local-functions-in-scripts.html

As others have said, you need to put your functions in another file.

0
source

All Articles