Problem 214. Filter values in a vector
Cody often benefits from a functional style of programming. For example, your score is often better when you compose multiple functions instead of using intermediate variables. This problem involves creating a function to expand the repertoire of "functional functions."
For this problem, write a filter function that applies a "predicate" function to a numeric, character, or cell vector and returns the elements for which the predicate returns true. Here are few examples:
filterfun(@isprime, 1:10) ==> [2 3 5 7] filterfun(@(c)c~='a', 'kayak radar') ==> 'kyk rdr' filterfun(@(x)~isempty(x), {[]; 1; 'a'; []; {}}') ==> {1; 'a'}
Notes: If the vector v is a cell, you should apply the predicate to v{i} not v(i). Also, filterfun should preserve the singleton dimension of the vector, i.e. if the input vector is a column vector the output should be a column vector.
Solution Stats
Problem Comments
-
1 Comment
I think the third example in the problem statement is incorrect. The input is a row (it's set up as a column, but then is transposed), but the output is a column.
Solution Comments
Show commentsProblem Recent Solvers72
Suggested Problems
-
27770 Solvers
-
It dseon't mettar waht oedrr the lrettes in a wrod are.
1853 Solvers
-
Project Euler: Problem 6, Natural numbers, squares and sums.
2281 Solvers
-
Construct an index vector from two input vectors in vectorized fashion
395 Solvers
-
Get the elements of diagonal and antidiagonal for any m-by-n matrix
480 Solvers
More from this Author1
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!