如何使用循环命名变量并赋值。

28 views (last 30 days)
seakyven
seakyven on 23 May 2023
Answered: seakyven on 23 May 2023
我想设置三个矩阵,名字分别为botmun1,botmun2,botmun3.这三个矩阵分别是根据一个t矩阵和一个BOTMFN矩阵组合来的,
bottom_n1=zeros(250,8);
for i=1:250
for j=1:4
bottom_n1(i,2.0*j-1.0)=t(4.0*i-4.0+j,1);
bottom_n1(i,2.0*j)=BOTMFN(4.0*i-4.0+j,2);
end
end
bottom_n2=zeros(250,8);
for i=1:250
for j=1:4
bottom_n2(i,2.0*j-1.0)=t(4.0*i-4.0+j,1);
bottom_n2(i,2.0*j)=BOTMFN(4.0*i-4.0+j,3);
end
end
现在我不想一个一个的输入进去,想通过一个循环,因为这三个矩阵唯一的不同就是他们的名字的后缀分别为1、2、3以及在BOTMFN矩阵中对应的列的值。我从网上查了下,看到可以用eval函数来设置循环变量的名字,但是怎么跟矩阵结合起来呢?
我最后就是想变成一个类似这样的程序
for k=1:3
bottom_nk=zeros(250,8);
for i=1:250
for j=1:4
bottom_nk(i,2.0*j-1.0)=t(4.0*i-4.0+j,1);
bottom_nk(i,2.0*j)=BOTMFN(4.0*i-4.0+j,k+1);
end
end
end
当然我这个程序肯定是不对的。想着使用num2str,但是不知道该怎么用。。只要求论坛大牛们的帮助。谢谢~

Accepted Answer

seakyven
seakyven on 23 May 2023
试试这样
for k=1:3
eval(['bottom_n',num2str(k),'=[]']);
for i=1:250
    for j=1:4
        eval(['bottom_n',num2str(k),'(',num2str(i),',',num2str(2.0*j-1.0),')=',num2str(t(4.0*i-4.0+j,1)),';']);
        
    end
end
end

More Answers (0)

Categories

Find more on 启动和关闭 in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!