且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我如何在scilab中的i = 1..10循环中创建变量Ai

更新时间:2021-09-10 03:35:03

如果您的意图正确,那么您想使用动态变量名(变量名不是硬编码的,而是在执行过程中生成的).正确吗?

If I get your intention right, you want to use dynamic variable names (=variable names are not hardcoded but generated during execution). Is that correct?

就像其他人在链接的帖子中(以及其他许多地方)所指出的那样,例如

As others already pointed out in the linked posts (and at many other places, e.g. here), in general it is not advisable to do this. It's better to use vectors or matrices (2D or 3D), if your variables have the same size and type, e.g. if

A1=[1,2];
A2=[3,4];

更好的方式:

A(1,1:2)=[1,2];
A(2,1:2)=[3,4];

这样,您可以将变量存储为更有效的矩阵形式,该形式执行速度更快(循环很慢!),并且通常更灵活地作为独立变量(您可以定义它们的某个子集,并执行矩阵运算等). )

This way you can store the variables in a more efficient matrix form, which executes faster (loops are slow!) and generally more flexible as independent variables (you can define a certain subset of them, and execute matrix operations, etc.)

但是,如果您确实要执行此操作,请使用execstr:

However if you really want to do it, use execstr:

clear;  //clear all variables
for i=1:10
  execstr("A"+string(i)+"=[]");   //initialize Ai as empty matrix
  execstr("B"+string(i)+"=0");    //initialize Bi as 0
  execstr("C"+string(i)+"=zeros(2,3)");   //initialize Ci as 2*3 zero matrix
  execstr("D"+string(i)+"=1:i");   //initialize Di as different length vectors
end
disp(A1,"A1");
disp(B2,"B2");
disp(C3,"C3");
disp(D1,"D1");
disp(D5,"D5");

如果变量名称仅在显示结果时很重要,则可以使索引显示为变量名称的一部分,例如:

If variable names are only important when you display the results, you can make the indices to appear as part of the variable name, e.g.:

E=0.1:2:8.1;      //vector with 4 elements
disp(E,"E");
for j=1:4
  mprintf("\nE%i = %.1f",j,E(j));  //appears as 4 different variables on the screen

end