Info

i wanna improve my function

1 view (last 30 days)
asaf omer on 2 Jul 2019
Closed: MATLAB Answer Bot on 20 Aug 2021
hola . i try to write a function that finds out if a vector is contained witin another vector (short and long)
so far i got this one(look below) , but i wanna improve it so the function will check it for the next values and not only for the first values.
for exmple for the vectors:
[2,3], [2,3,4]
the ans will be 1
but for [3,4],[2,3,4]
the ans will be 0
-------------
function [res] =contain(v,u)
res=true;
for i = 1: length(v)
if v(i)==u(i)
i=i+1;
res=true;
else
res=false;
end
end
-----------------
thanks!!
Geoff Hayes on 2 Jul 2019
asaf - your code starts with the v and checks to see if it is in u, but maybe you should consider the elements of u first. If your code were to iterate over u (I'm assuming you have to use a for loop and cannot use other built-in MATLAB functions) then check to see if u(k) matches v(1). If identical, then you can check to see if the remaining elements of v follow u(k). If so, then you are done. If not, then you continue iterating over u until the another element of u matches the first element of v. etc.

infinity on 2 Jul 2019
Hello,
As guided by @Geoff Hayes, I could give an example code here.
function [res] =contain(v,u)
res=true;
idx = find(u == v(1));
for i = 1:length(v)
if v(i)==u(i+idx(1)-1)
% i=i+1;
res=true;
else
res=false;
end
end
Actually, to get a function with the goal of checking wheather or not a matrix is a part of anther matrix, many approaches can be done. Here, I follow your idea and give above suggestion.