evalin with variable - MatLab - matlab

I'm trying to do something like evalin('base','mat(x)', 4), where mat is a matrix in my main script, and x is a variable in the function I'm running this from. How can I use the x variable in there?

Try this:
evalin('base',['mat(' num2str(x) ')'])
This substitutes x for the value it has in your function, and uses that value to build the string that is passed to evalin.

Related

Making symbolic functions without hard-coding in MATLAB

I want to make symbolic functions theta1(t), theta2(t), theta3(t),...,thetaN(t) where N is some parameter I can define in MATLAB. I know that I can use something like sym('theta',[1 N]) to get [theta1, theta2, theta3,..., thetaN]. However, how can I do the same thing with theta being a function of t? The way to hard-code it would be like syms theta1(t) theta2(t) theta3(t) ... thetaN(t), but I want to make this general.
I do not want to directly use the sym command here because "support of character vectors that are not valid variable names and do not define a number will be removed in a future release", meaning something like sym('theta1(t)') would not be valid in future releases.
Any suggestions?
Figured part of it out. I could do something like the following
for i = 1:N
syms(strcat('theta',num2str(i),'(t)'))
end
However, if I want to assign a variable that contains all the symbolic expressions I'm still stuck. If I try
for i = 1:N
my_array(i) = syms(strcat('theta',num2str(i),'(t)'))
end
I get Error using syms (line 133). Using input and output arguments simultaneously is not supported. It works if I use sym instead of syms, but this leads to the warning I mentioned in my original post.

variable namespace in matlab

Recently I found a problem in matlab code when calling assignin('caller',...) in a function to make new variables in the caller function, if the variable name is the same name as a matlab function name in the path.
Here is a simple code snippet just to demonstrate the problem.
function myfunctest
sin = 0;
subfcn_set; % call subfcn_set to make a new variable
whos % list variables in current workspace
sin % raise error because it calls the sin function
end
function subfcn_set
assignin('caller', 'sin', 'I am sine');
end
save the snippet into myfunctest.m and run it in matlab
>> myfunctest
Name Size Bytes Class Attributes
sin 1x9 18 char
sin =
I am sine
Everything looks good. But if I delete sin = 0 in myfunctest and run it again,
>> myfunctest
Name Size Bytes Class Attributes
sin 1x9 18 char
Error using sin
Not enough input arguments.
Error in myfunctest (line 8)
sin
The builtin sin function is called even if the the variable sin existed as indicated by whos. This applies to other matlab function names in the path too.
If we change the variable name from sin to some other thing, e.g., notafunc, everything looks good regardless the initialization.
>> myfunctest
Name Size Bytes Class Attributes
notafunc 1x13 26 char
notafunc =
I am notafunc
This is actually not a "problem". From the documentation of assignin:
assignin(ws, 'var', val) assigns the value val to the variable var in the workspace ws. The var input must be the array name only; it cannot contain array indices. If var does not exist in the specified workspace, assignin creates it.
Since there is a function sin() existing in the namespace matlab does not create the variable.
Apart from this I would not recommend this approach since it will confuse other persons using your code. In case you do not know that this line exists, you will not realize what happens. An exception can be made for subfunctions to other functions, in case the subfunctions are defined in the same .m file as the function using the subfunctions. However, even then it should be used sparsely in case the file is large.

Saving variables within a function? (MATLAB)

I have a function that goes something like this:
function [] = function1
-variable1= value1;
-variable2= value2;
-matrix1=[]
-matrix2=[]
-loops that fill in matrix1 and matrix2
-more declarations
-final function1 end
function2[]
takes values from function 1 and does stuff, creates new variables
funcion2 end
function3[] that uses values from function 2 and function4[] that uses function 3.
(Sorry for all of that by the way). Now, my question is, is there anyway to save variables, arrays, etc. in the workspace for later analysis? All 4 functions are on the same tab in the MATLAB editor.
To save any particular variable from workspace in Matlab you should execute the following
save('Name of the mat file','Name of the variable')
To save multiple variable the command shall be
save('name of the mat file','var1','var2'...)
variable can be array, matrix, structure, double anything. For any other use of the function save please docsearch it in the command prompt

MATLAB symbolic variables couldn't be used in nested function

I have a MATLAB function to solve a Inertia Tensor , and I have a nested function in my program . All the variables in it are symbolics but it told me
“Error using assignin: Attempt to add ”x“ to a static workspace”
and I don't understand why this happens . Here is my test.m code:
function test
syms x y z
f=x
f1=f+1
f2=f1^2
function r=test2
r=f2^3;
end
f3=test2
end
After searching this web-forum I have found some answers . But at the same time I just don't understand it
Andrew Janke explianed it like this : While syms A may look like a static variable declaration, it isn't. It's just a regular function call. It's using Matlab's "command" invocation style to look like syntax, but it's really equivalent to syms('a', 'b', 'c').
on this page : Matlab: "Error using assignin: Attempt to add "c" to a static workspace"
what does static variable mean ?
I also search the HELP doc and it said :In functions and scripts, do not use syms to create symbolic variables with the same names as MATLAB® functions. For these names MATLAB does not create symbolic variables, but keeps the names assigned to the functions.
I only know syms x to create a symbolic variable in the workspace but why does the documentation say MATLAB does not create ?
'Static' means fixed, 'workspace' is what Matlab calls the places where all of its variables are stored. For non-nested functions the workspace starts off as empty when Matlab is at the beginning of the function; as Matlab continues through function's lines of code it continuously add more variables to the workspace.
For functions with a nested function, Matlab first parses the function to see what variable will be created (it specifically looks for x = type lines), then it creates all of these variables (with value as 'unassigned'), and then only does it start to run through the code; but while running through the code, it can never create a new variable.
This is why the code
function TestNestedFunction
syms x;
function Nested()
end
end
generates an error, there is no x = to tell it to pre-create the unassigned variable x at the start of the code. It fails at syms x;, as that line tries to create a new variable x, which fails as it may not.
This is also why the following code runs
function TestNestedFunction
syms x;
x = x;
function Nested()
end
end
it sees the x = and then pre-creates x. (This is why your example of adding [x, y, z] = deal([]); also works).
You can test this with a break point at the beginning of simple non-nested function and a simple nested function. Just run it step by step.
This code works:
function test
x=sym('x')
y=sym('y')
z=sym('z')
f=x
f1=f+1
f2=f1^2
function r=test2
r=f2^3;
end
f3=test2
end
I think the pages you found are quite clear.
You need to declare the variables one by one and use:
x = sym('x')
Otherwise syms will try to assign the values into a workspace where this is not allowed.

make matlab variable in workspace as global

In the workspace I make a matrix .
Now I can access the variable in script. Like doing Variable(2) will return 4.
But inside a function like
function y= getvariable(x)
y=Variable(x)
end
I get error
y=getvariable(2)
??? Undefined function or method 'Variable' for input
arguments of type 'double'.
Error in ==> getvariable at 3
y=Variable(x)
So how to make the Variable matrix global so that I can access it through any function?
Although you could use globals
>> global Variable = rand(50,12);
...
function y = getvariable(x)
% Always needed
global Variable;
% Here ya go
y = Variable;
end
the MUCH better alternative is to use
function x = getvariable(x)
% no body needed
end
which you call as
>> y = getvariable(Variable);
(Of course, for this contrived example, this would just be equal to
>> y = Variable;
)
Although there are some legitimate use cases for global variables, in general they tend to spaghettify your code and make it far more bug-prone and much harder to debug. Have a read on the subject.
As #rody suggested, pass the matrix and the x inside the function
I am just giving an example to make things clear.
Like you want to access the 10th element of Variable matrix, so make the function as
function y= getvariable(matrixname,no)
y=matrixname(no)
end
If you want to access 3rd element of Variable, so you type
y=getvariable(Variable,3)
you will get 3rd element
call global Variable before you define it in your workspace
call global Variable before you use it in your function
However I suggest you think of other ways to pass variables to your function, as globals might cause difficulties during debugging.