Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

Matlab: Automatically create cell array with name with meaning

I would like to name variable (type double) in the following way:

k0 = D(1,1);
k1 = D(2,2);
k2 = D(3,3);
k3 = D(4,4);
k4 = D(5,5);
k5 = D(6,6);
k6 = D(7,7);
k7 = D(8,8);
...

up to k99 automatically using for loop. So I see that I should use array or cell instead of double variable using eval as it is slow. But if I should use array or cell instead of double variable, I have to start at k{1} or k(1), which loses the meaning as I want exactly that k0 refers to D(1,1), i.e. the number in my variable is 1 less. How do I create meaningful cell name like k{0}?

Also, say I have an array A. There are also some times i need meaningful variable name, such as

c111 = A(1)*A(1)*A(1)
c222 = A(2)*A(2)*A(2)
c333 = A(3)*A(3)*A(3)

How can I create c{111} efficiently using for loop?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use structures:

D = rand(21);
c = 1;
for k = -10:10
    if k<0
        s.(['k_' num2str(abs(k))]) = D(c,c);
    else
        s.(['k' num2str(k)]) = D(c,c);
    end
    c = c+1;
end

This will give you a structure like:

s = 

     k_10: 0.51785
     k_9: 0.90121
     k_8: 0.40746
     k_7: 0.092989
     .
     .
     k_1: 0.75522
     k0: 0.55257
     k1: 0.28708
     .
     .
     k9: 0.94182
     k10: 0.2124

and don't use eval...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...