2

forネストされた形式のループが2つあります。2番目のループは最終的な方程式を計算します。結果の表示は、2番目のループが完了したときに表示するために、2番目のループの外側にあります。

以下は、MATLABで使用したロジックです。vsxのグラフをプロットする必要がありますeqn2

L=100
for x=1:10
    eqn1
       for y=1:L
          eqn2
       end 
       value = num2strn eqn2
       disp value
end

現在私が直面している問題は、の値または出力が10に達するeqn2まで各サイクルの後に常に置き換えられることですx。したがって、andvalueのワークスペーステーブルにeqn2は最後の値のみが表示されます。value私の意図は、1:10からのxのすべてのサイクルでのすべての出力値を文書化することです。

これどうやってするの?

4

1 に答える 1

1

あなたは私の好みには少し強すぎる疑似コーディングをしました - 私はあなたがやろうとしていたことを再構築しようとしました. 私が正しく理解していれば、これはあなたの質問に対処するはずです(計算の中間結果を配列Zに保存します):

L=100
z = zeros(L,10);
for x=1:10
   % perform some calculations
   eqn1
   for y=1:L
   % perform some more calculations; it is not clear whether the result of 
   % this loop over y=1:L yields one value, or L. I am going to assume L values
       z(y, x) = eqn2(x, y)
   end 

   value =num2strn eqn2

   disp value
end

% now you have the value of each evaluation of the innermost loop available. You can plot it as follows:

figure; 
plot( x, z); % multiple plots with a common x parameter; may need to use Z' (transpose)...
title 'this is my plot'; 
xlabel 'this is the x axis'; 
ylabel 'this is the y axis';

コメントで尋ねたその他の質問については、次の情報からインスピレーションを得られる可能性があります。

L = 100;
nx = 20; ny = 99;  % I am choosing how many x and y values to test
Z = zeros(ny, nx); % allocate space for the results
x = linspace(0, 10, nx); % x and y don't need to be integers
y = linspace(1, L, ny);
myFlag = 0;              % flag can be used for breaking out of both loops

for xi = 1:nx            % xi and yi are integers
    for yi = 1:ny
         % evaluate "some function" of x(xi) and y(yi)
         % note that these are not constrained to be integers
         Z(yi, xi) = (x(xi)-4).^2 + 3*(y(yi)-5).^2+2;

         % the break condition you were asking for
         if Z(yi, xi) < 5
             fprintf(1, 'Z less than 5 with x=%.1f and y=%.1f\n', x(xi), y(yi));
             myFlag = 1; % set flag so we break out of both loops
             break
         end
    end
    if myFlag==1, break; end % break out of the outer loop as well
end

これはあなたが考えていたものではないかもしれません-「z(y、x)のすべての値が5未満になるまでループを実行し、xを出力する必要がある」ことを理解できません。外側のループを完了するまで実行すると (これが「z(y,x) のすべての値」を知る唯一の方法です)、x の値は最後の値になります...これが、実行することを提案していた理由ですx と y のすべての値を取得し、行列 Z 全体を収集してから、必要なものについて Z を調べます。

たとえば、すべての Z < 5 である X の値があるかどうか疑問に思っている場合は、次のようにすることができます (forループから抜け出さなかった場合)。

highestZ = max(Z, [], 1); % "take the highest value of Z in the 1 dimension
fprintf(1, 'Z is always < 5 for x = %d\n', x(highestZ<5));

ここで分からなかったら諦めます…

于 2013-02-07T05:14:07.517 に答える