Non riesco a capire come funziona il ciclo iterativo for

di Anonimizzato30925 il
1 risposte
Salve, premetto subito che sono alle primissime armi con l'uso di Matlab. Vorrei chiedervi come posso capire come usare il ciclo for? per comandi come l'if sono riuscita a ingranare abbastanza velocemente e riesco a "viasualizzare" e impostare semplici problemi, invece con il for non riesco ad impostare nemmeno un problema che calcoli la media di 8 numeri interi. Qualcuno potrebbe spiegarmelo? magari non con la classica definizione perchè quella la ho già

1 Risposte

  • I cicli for (e while) sono alla base della programmazione, a prescindere dal linguaggio specifico.
    TI consiglio di cominciare con gli elementi base della programmazione in MatLab:
    https://www.mathworks.com/help/matlab/getting-started-with-matlab.html

    Nello specifico, per il ciclo for


    Nell'esempio che segue, viene calcolata la medio di un vettore di 10 numeri interi random.
    I commenti nel codice dovrebbero spiegare con sufficiente dettaglio il funzionamento del loop.

    Nel secondo esempio per lo stesso codice, vengono stampate nella command window i valori delle variabili intermedie; questo dovrebbe facilitare la comprensione

    Prova anche ad eseguire il codice in modalità debug
    https://it.mathworks.com/help/matlab/matlab_prog/debugging-process-and-features.html
    
    % Define the size of the input array
    n_num=10;
    % Define the input values as an array of random integer values between 1 and 100
    num=randi([1 100],1,n_num);
    % Initialize the value of the sum of the numbers
    num_sum=0;
    % Loop over the input array
    % loop_idx ==> index of the loop used to access to the i-th element of the array
    % 1 ==> the first element of the array
    % : colon operator
    % n_num ==> upper limit of the loop
    for loop_idx=1:n_num
       % At each iteration the the value of the index (loop_idx) is automatically incremented
       % Its value is used to access, sequentially, to the alement of the array
       % At each iteration the i-th value of the array is added to the "num_sum"
       % variable that holds the summ of the element of the array
       num_sum=num_sum+num(loop_idx);
    end
    % At the end of the loop, the sum of the elements of the array is divided by the
    % the number of the elements of the array to compute the mean of the array
    num_mean=num_sum/n_num
    
    fprintf('\n\n\n')
    % To "see" what happens in the loop:
    
    num_sum=0;
    for loop_idx=1:n_num
       fprintf('loop index loop_idx=%d\n',loop_idx)
       fprintf('current element of the array num(%d)=%d\n',loop_idx,num(loop_idx))
       fprintf('Previous value of the sum=%d\n',num_sum)
       num_sum=num_sum+num(loop_idx);
       fprintf('Current value of the sum=%d\n\n',num_sum)
    end
    num_mean=num_sum/n_num;
    fprintf('Mean of the array=%d\n',num_mean)
    
Devi accedere o registrarti per scrivere nel forum
1 risposte