Function with subfunction inside
2 views (last 30 days)
Show older comments
The function func takes any real array A as input and outputs an array B of equal size, whose entries are equal to twice the corresponding entry of A for every nonnegative entry of A, and equal to a given number n, for every negative entry of A. The function func accepts a subfunction subf. Complete the code in func and subf, as necessary.
function B=func(A,n)
% Replace A by B such that each entry of B equals:
% twice the entry of A if that entry of A is non-negative
% or n if the entry of A is negative
B = 2*subf(_______________ % COMPLETE THE ARGUMENT LIST
function C = subf(__________________ % COMPLETE THE
% ARGUMENT LIST
% subfunction of func
C___________________________________ % COMPLETE THE LINE
I am totally confused on this problem. With so few lines of code, how do I get it to distinguish whether the entry of A is negative or nonnegative.
I guess I would be
B = 2*sub(A)
C = subf(A<0,n)
C = n
0 Comments
Answers (1)
Image Analyst
on 2 Aug 2014
You need to use logical indexing to figure out where A is positive. For example
positiveValueLocations = A > 0; % Vector of 0's and 1's.
Now you can set those locations to twice the value
B=A; % Initialize
B(positiveValueLocations) = 2 * A(positiveValueLocations);
That's enough hint. Look up logical indexing if you want to know more. It should be trivial to set B = n for the other locations. There are two ways to do it: one by initializing to n and another by assigning values that aren't positiveValueLocations to n. I don't see any need whatsoever for any subfunction or for a variable C.
2 Comments
Image Analyst
on 2 Aug 2014
Well it's kind of stupid, but to do it that dumb way you'd have to pass in A and ninto subf(), then do what I say to pass back A but with n/2 wherever A<=0. So C = A but with elements of A = n/2 wherever A<=0.
See Also
Categories
Find more on Whos in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!