如何设置for循环次数限制并打破for循环?

时间:2016-12-20 08:21:49

标签: matlab for-loop

我会输入数字1~22。 (因为数字是22。)

(ex)当我输入1时,显示图(1)。 )

现在我想将此循环的时间限制设置为22。

因为即使我输入所有这些,也不能满22岁。

并且我想知道如何在不键入所有数字(小于22)的情况下结束此循环。

我将显示我写的代码,请给我建议。

for TNP=1:23     
**% for-loop's end condition -->1. when i type all 22 number. 
                        ->2. when i type 23 to end the for-loop without typing more number.**

   FN = input('Which figure do you want: ')   **% here i would type the number of figure.**

  if FN==1
   F1=meshc(z(:,111:268))
   grid on
   hold on

  elseif FN==2
   F2=meshc(z(:,269:419))
   grid on
   hold on

  elseif FN==3
   F3=meshc(z(:,431:586))
   grid on
   hold on
. 
. 
.
  else FN=23
   close;
  end

end   
**% but even i add the 'break' for-loop doesn't end. what is the reason??** 

2 个答案:

答案 0 :(得分:0)

你不能在这里使用循环。

当您想要重复某些特定次数的代码时,会使用循环,这不是这里的情况(如果我理解正确的话)。

您想要的是接受1到22之间的输入以显示相应的数字。我认为数字不必按顺序排列(否则你不需要手动输入)

你必须首先定义一个完成循环的数字(例如-1),然后使用一段时间。

FN = input('Which figure do you want (1 to 22, or -1 to exit)?: ')
while FN ~= -1
    if FN < 1 | FN > 22
        disp (['Incorrect option: ' num2str(FN)]);
    else
        % your code to handle correct cases here
    end
    % now ask again
    FN = input('Which figure do you want (1 to 22, or -1 to exit)?: ')
end

答案 1 :(得分:0)

我同意SembeiNorimaki - 您选择的设计有点奇怪。我会选择与他/她写的相似的东西:

function myfcn()

    % (define Z here)

    % User input loop        
    while true

        % Get the number
        FN = input('Which figure do you want: ');            

        % Don't ever trust the user, even if 
        % the only user is you
        if ~isnumeric(FN) || ...
                ~isscalar(FN) || ....
                ~isfinite(FN) || ...
                ~isreal(FN) || ...
                FN > 23 || ...
                FN < 0

            warning([mfilename ':invalid_input'],...
                    'Invalid input; please insert a figure number 1-23, or 0 to exit.');
            continue;

        end

        % It's always good to have an explicit exit condition
        if FN == 0
            break; end

        % Apparently, you want this to be a special case
        % (Note that this will only close the last figure drawn)
        if FN == 23
            close; end

        % Call a handler to do all the heavy lifting
        h = myGraphicsHandler(z, round(FN));

        % ...Do whatever you want with this handle

    end

end

function h = myGraphicsHandler(z, FN)

    % These are the only things that seem to be 
    % different between each case
    rangesTable = {111:268
                   269:419
                   431:586  % ... and so on
                  };

    % create the figure
    h = figure;
    hold on
    meshc(z(:, rangesTable{FN}));
    grid on    

    % ... other operations / figure decorations here

end