How can I create variables Ai in loop in scilab, where i=1..10

寵の児 提交于 2019-12-25 04:28:10

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/32482073/how-can-i-create-variables-ai-in-loop-in-scilab-where-i-1-10

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!