Create variables and vectors dynamically

6 visualizaciones (últimos 30 días)
CarAnAlb
CarAnAlb el 16 de Feb. de 2018
Editada: Ayush Modi el 28 de Ag. de 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.

Respuestas (1)

Ayush Modi
Ayush Modi el 28 de Ag. de 2024
Editada: Ayush Modi el 28 de Ag. de 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":

Categorías

Más información sobre Statistics and Machine Learning Toolbox en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by