[Scilab-users] Loop query

Lester Anderson arctica1963 at gmail.com
Sun Aug 15 11:28:11 CEST 2021


Hello Samuel,

The size of ns (number of steps) and seq (sequence of values) are variable
depending on the integer input, and this seems to be one issue. So I guess
the problem is how to allocate dynamic arrays where you do not know the
final size?

This is a direct translation of a Matlab function:

function [ns, seq]=collatz(n)

// Translation of Matlab function// First number in the sequence is
nseq(1) = n;// Position an index on the next element of the sequencei
= 2;
// Repeat the iteration until you find a 1while seq(i-1) ~= 1
    // Use a modulus after division to find an even/odd number
    if modulo(seq(i-1), 2) == 0
        // Step taken if even
        seq(i) = seq(i-1)/2;
    else
        // Step taken if odd
        seq(i) = 3*seq(i-1) + 1;
    end
    // Increment index
    i = i+1;end// Find the length of the sequencens = length(seq);endfunction


Lester

On Sun, 15 Aug 2021 at 09:24, Samuel Gougeon <sgougeon at free.fr> wrote:

> Le 15/08/2021 à 09:00, Lester Anderson a écrit :
>
> Hello,
>
> Basic query. I have a simple code that applies the Collatz conjecture
> equation (3n+1) by running a function and then runs a loop over the values
> stored in prime (the first 8 Prime numbers):
>
> clear
>
> exec('collatz.sci',-1);
> prime = primes(20);
> for i = 1:length(prime)
>     [ns, seq]=collatz(prime(i))end
>
> As it stands, this just runs to the end (i=8) and the value 19. How can I
> get the code to write the results of each loop pass into the variables ns
> and seq, such that each contains the results of the 8 passes?
>
>
> This runs all the 8 iterations, but each next iteration overwrites ns and
> seq.
> What are the sizes of ns and seq ?
>
> _______________________________________________
> users mailing list
> users at lists.scilab.org
> http://lists.scilab.org/mailman/listinfo/users
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.scilab.org/pipermail/users/attachments/20210815/516fbb1c/attachment.htm>


More information about the users mailing list