help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: a try-if construction


From: Vic Norton
Subject: Re: a try-if construction
Date: Wed, 10 Jun 2015 07:03:03 -0400

On Jun 9, 2015, at 5:32 PM, Vic Norton <address@hidden> wrote:

> The perl code
> 
>   my @K= qw( 1   30   48 );
>   my $n = 109;
>   my ($k0, $k1);
>   my $i = 0;
>   for (my $i = 0; $i < @K; $i++) {
>     $k0 = $K[$i];
>     unless ($k1 = $K[$i + 1]) { $k1 = $n }
>     printf("i = %d, k0 = %d, k1 = %d\n", $i + 1, $k0, $k1);
>   }
> 
> and the octave code
> 
>   K = [ 1   30   48 ];
>   n = 109;
>   for i = 1 : length(K)
>     k0 = K(i);
>     try k1 = K(i + 1); end
>     if k1 == k0; k1 = n; endif
>     printf("i = %d, k0 = %d, k1 = %d\n", i, k0, k1);
>   endfor
> 
> produce exactly the same results:
> 
>   i = 1, k0 = 1, k1 = 30
>   i = 2, k0 = 30, k1 = 48
>   i = 3, k0 = 48, k1 = 109
> 
> I am very comfortable with the "unless" line in perl. I am much less 
> comfortable with the "try-if" lines in octave. Is this "try-if construction 
> the best way to do what I want to do?

On Jun 10, 2015, at 3:53 AM, JokerOne <address@hidden> wrote:

> Hi Vic,
> 
> to be honest, I do not fully understand what you actually want to do?
> 
> For the output you got, maybe something like that is more straightforward?
> 
>   K = [ 1   30   48 ];
>   n = 109;
>   K_helper = [K,n]; % "attach" n to K
> 
>   for i = 1 : (length(K_helper)-1)
> 
>       k0 = K_helper(i);
>       k1 = K_helper(i+1);
>       printf("i = %d, k0 = %d, k1 = %d\n", i, k0, k1);
> 
>   endfor

I guess I wasn't very clear. Suppose you have a list of "actions" you want to 
take and a default action in case one or more of the actions is impossible. In 
Perl you simply run through the list, taking the default action UNLESS you CAN 
take the listed action.

How do I do the same thing in Octave? I want to TRY each action and, if I CAN'T 
take it, take the default. The Perl mechanism is extremely simple and logical. 
Is there a simple and logical Octave mechanism to implement this process?

Now I think I've answered my question. The following TRY-IF Octave construction 
seems to duplicate the Perl mechanism.

   K = [ 1   30   48 ];
   n = 109;
   for i = 1 : length(K)
     k0 = K(i);
     k1 = n;                     % take the default action
     try k1 = K(i + 1); end      % unless the action works
     printf("i = %d, k0 = %d, k1 = %d\n", i, k0, k1);
   endfor

with the output

   i = 1, k0 = 1, k1 = 30
   i = 2, k0 = 30, k1 = 48
   i = 3, k0 = 48, k1 = 109




reply via email to

[Prev in Thread] Current Thread [Next in Thread]