0

関数を実行して、3 つの異なる出力変数を作成したいと考えています。

for i=1:3
    for j=1:3
Rent_nb = landrent(i,j,Dist);
    end 
end

そして、「_nb」を 1、2、3 にしたいので、3 つの出力配列を取得します。だから私はインターネットを見たところ、これを使用しなければならないことがわかりました:
http://www.mathworks.com/matlabcentral/answers/29712-creating-a-new-variable-in-each-iteration

それは私に与えるでしょう:

for i=1:3
    for j=1:3
eval(['rent' num2str(i) '= landrent(i,j,Dist_lowcost)']);
    end 
end

これは機能しているようですが、よくわかりません... 3 ではなく 9 つの出力 (i と j の組み合わせごとに 1 つ) を取得したいと思います。この部分と関係があると思います: num2str(i ..しかし、これがどのように機能するのか、何をするのかはよくわかりません。誰かが説明/助けてくれますか?

ありがとう

4

1 に答える 1

1

It may help to write out the command separately (to a string) and then evaluate it, and so you will be able to see exactly what statement is being evaluated:

for i=1:3
    for j=1:3
        cmd = ['rent' num2str(i) '= landrent(i,j,Dist_lowcost);'];
        fprintf('command to evaluate is: %s\n',cmd);  % or just step through the code
        eval(cmd);
    end 
end

The output from the above for i==1 is

command to evaluate is: rent1= landrent(i,j,Dist_lowcost)
command to evaluate is: rent1= landrent(i,j,Dist_lowcost)
command to evaluate is: rent1= landrent(i,j,Dist_lowcost)

Note that for every j, we reset rent1 to landrent(i,j,Dist_lowcost) and so that is why you are only getting three outputs - each subsequent iteration over j replaces the previous result.

If you are determined to go ahead with the above and create new variables rather than using a matrix, you could do the following instead - create the renti vector at each iteration of i and then use that as you iterate over j:

for i=1:3
    cmd = ['rent' num2str(i) '=zeros(1,3);'];
    eval(cmd);
    for j=1:3
        cmd = ['rent' num2str(i) '(j)= landrent(i,j,Dist_lowcost);'];
        fprintf('cmd=%s\n',cmd);
        eval(cmd);
    end 
end
于 2014-06-01T19:34:38.937 に答える