Clear Filters
Clear Filters

Info

This question is closed. Reopen it to edit or answer.

i wanna improve my function

1 view (last 30 days)
asaf omer
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!!
  1 Comment
Geoff Hayes
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.

Answers (1)

infinity
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.

This question is closed.

Products

Community Treasure Hunt

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

Start Hunting!