Problem 57775. Easy Sequences 102: One-line Code Challenge - Take While Function

takeWhile is another useful functional programming construct. The takewhile function is similar to the built-in function arrayfun, but unlike arrayfun, takewhile is applied to an input array of indefinite length.
We shall define takeWhile as a function that accepts 2 function handle and an integer as inputs, and outputs a row vector. The first function input, A, defines a sequence with the natural numbers as domain. The second function input C, is a conditional function, while the third argument n, is the starting number. takeWhile applies A to all consecutive positive numbers starting with n, as long as the condition in C is met and stops as soon as C is no longer satisfied.
The following examples will make this concept clearer:
>> % Example #1
>> A = @(x) 2*x; C = @(y) y < 30;
>> takeWhile(A,C,5)
>> ans =
>> 10 12 14 16 18 20 22 24 26 28
>> % Example #2
>> A = @(x) cosd(10*x) + 1; C = @(y) y >= 1;
>> takeWhile(A,C,1)
>> ans =
>> 1.9848 1.9397 1.8660 1.7660 1.6428 1.5000 1.3420 1.1736 1.0000
In the first example, function A outputs the set of even numbers starting from 10, but function C limits the output to only those that are less than 30.
In the second example, the trigonometric function A, is applied while the value of the A is greater than or equal to 1. A is applied to n = 1 to 9 and then takeWhile stops, since if n = 10, A = cosd(10*10)+1 = 0.8264 < 1.
In this problem we are asked to implement the takeWhile function, with the following restrictions:
  • The function should only have one (1) line of code, excluding the function start line.
  • Semicolons (;) are considered end-of-line characters.
  • Please suppress the function end line. Keyword 'end' is not allowed.
  • Regular expressions and string manipulation are not allowed.

Solution Stats

0.0% Correct | 100.0% Incorrect
Last Solution submitted on Apr 28, 2024

Solution Comments

Show comments

Problem Recent Solvers0

No solvers yet, be the first player to solve this problem.

Suggested Problems

More from this Author116

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!