Reverse-Engineering Find Function

Consider the MATLAB relational operations: k = (a <= b); m = find(a <= b); where a is a real-valued row vector and b is either a real-valued row vector of the same length as a, or, a scalar.
The objective of this problem is to reverse-engineer MATLAB’s built in function find.
I have to write a MATLAB function, [m,k] = my_find(a,b); that implements the above relational operations using for-loops and if-statements only and does not use find.
The outputs k,m must be the same as those above, and k must be of type logical.
So far, I have:
function [m,k]=my_find(a,b)
for i=1:length(a)
if a<=b
k=1
m=a(a<=b)
else
k=0
end
end
However, when I run the script for the values
a=[1 2 0 -3 7]
b=[3 2 4 -1 7]
I get k=1 as a scalar and not as a vector of 1s. The result for m is correct though, m=[1 2 0 -3 7].
How can I get k to show me the results as a vector of values for all of the elements of a, instead of just the first element being repeated?
I have tried this with a different set of values, and k still sticks to the value of the first element.

 Accepted Answer

if a(i) <= b(i)
but you are going to have to work more on returning the indices.

3 Comments

And you need to determine whether b is a scalar or a vector with the same size as a.
I used a(i) <= b(i) and it properly returns the different values of k as they should be. However, if b is a scalar, then I get an error because there is only one element in b, and it cannot access an index beyond 1. Is it possible to use a for loop to indicate whether b is a scalar or a vector?
I have to use the same function for all conditions, so I don't think I am allowed to create a subfunction or separate function for when be is a scalar.
Thanks for all the help.
Well, you'll have to determine the sizes of both inputs, then make cases handling the different possibilities a scalar b 1-D array, a and b 1-D arrays and so on...

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!