Create variables and vectors dynamically

2 ビュー (過去 30 日間)
CarAnAlb
CarAnAlb 2018 年 2 月 16 日
編集済み: Ayush Modi 2024 年 8 月 28 日
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 Center および File ExchangeEntering Commands についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by