How can I create variables Ai in loop in scilab, w

2019-09-08 08:17发布

I'm using scilab. Basically i want the same as this guy Create 'n' matrices in a loop or this guy http://www.mit.edu/~pwb/cssm/matlab-faq_4.html#evalcell

The answer is not working in scilab, and I can not manage it to do the same in scilab. Can someone help me.

标签: loops scilab
1条回答
虎瘦雄心在
2楼-- · 2019-09-08 08:27

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];

Better way:

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.)

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
查看更多
登录 后发表回答