Create variables and vectors dynamically

6 views (last 30 days)
CarAnAlb
CarAnAlb on 16 Feb 2018
Edited: Ayush Modi on 28 Aug 2024
Hi all, I write to find alternatives. I habe implemented the next code, it works, but I wonder if is there an optimum routine or command already integrated in Matlab. I need strictly to create dynamic variables an with diese variable create vectors.
n = 3; % Number of iterations
c = sym(zeros(n,1));
for m=1:n
syms (sprintf('A%d', m)); % Create dynamically the variable
c(m) = sprintf('A%d', m); % Store the last variable on a vector
end
Thank you all in forward.

Answers (1)

Ayush Modi
Ayush Modi on 28 Aug 2024
Edited: Ayush Modi on 28 Aug 2024
Hi CarAnAlb,
MATLAB is optimized for operations involving matrices and vectors. The process of revising loop-based to use MATLAB matrix and vector operations is called "vectorization". Vectorized code often runs much faster than the corresponding code containing loops. You can optimize the code using vectorization. Here is the revised code for your reference:
n = 3;
m = 1:n; % Create a vector from 1 to n
c = sym('A', [n, 1]); % Create a symbolic vector with names A1, A2, ..., An
disp(c);
Note - I am assuming, you want to create the variables within a loop and store them in a vector.
Refer the following MathWorks documentation for more information on "vectorization":

Categories

Find more on Statistics and Machine Learning Toolbox in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!