Create variables and vectors dynamically

6 Ansichten (letzte 30 Tage)
CarAnAlb
CarAnAlb am 16 Feb. 2018
Bearbeitet: Ayush Modi am 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.

Antworten (1)

Ayush Modi
Ayush Modi am 28 Aug. 2024
Bearbeitet: Ayush Modi am 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":

Kategorien

Mehr zu Statistics and Machine Learning Toolbox finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by