Create variables and vectors dynamically

7 次查看(过去 30 天)
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.

回答(1 个)

Ayush Modi
Ayush Modi 2024-8-28
编辑:Ayush Modi 2024-8-28
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":

类别

Help CenterFile Exchange 中查找有关 Statistics and Machine Learning Toolbox 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by