how to make symbolic variable by loop as we want
26 views (last 30 days)
Steven Lord on 8 Jul 2022
so, can i assume that in matlab there is no method for creating symbolic variable by only known is no of variables.
Sure there is, just not as individual variables (which is generally discouraged, see this Answers post for an explaination why this is discouraged and several alternative approaches.)
In this case rather than creating a1, a2, etc. or using eval just call sym.
n = 4;
A = sym('a', [1, n])
Now you can use A(1) for , A(2) for , etc.
B = A(1)+2*A(2)+A(3).^3+A(4)./4
This makes substituting values in for elements of A easy.
subs(B, A, [16 9 4 1])
Let's check that subs gave us the correct result by performing the substitution manually.
check = 16 + (2*9) + (4^3) + (1/4)
check == 393/4
More Answers (3)
Aiswarya on 7 Jul 2022
The error unrecognized variable arises because str2sym does not add the variables contained in the string to the workspace. So when you try to use a1 it throws an error.
If you really want to add variables with symbolic names like a1,a2,a3,a4... then you can use a loop like:
eval(sprintf('a%d = i', i));
Instead of the 'i' given as second argument to sprintf you can give a desired value.
However, note that eval can be slow and it is much better to use matlab arrays for this purpose (sequence or array of data). Eg:
a = zeros(1,4);
a(i) = i % instead of assigning i you can replace it with your desired value
You can access these variables by a(1),a(2) and so on.
Hrusheekesh on 11 Jul 2022
I understand that you want to create multiple symbolic variables with one command.
The following example will illustrate how to achieve the same
syms(sym('a', [1 10]))
Please refer to the Create symbolic variable documentation for more information on how to create symbolic variables.
JVan on 27 Sep 2022 at 4:28
If you are wanting to do it in a for loop, it can also been done as folllows. Here I just chose n=3 but that was arbitrary.
% Create a symbolic varaible for each value of n
We can now call syms to see that all the variables were added