i wanna improve my function
Infos
Cette question est clôturée. Rouvrir pour modifier ou répondre.
Afficher commentaires plus anciens
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 commentaire
Geoff Hayes
le 2 Juil 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.
Réponses (1)
infinity
le 2 Juil 2019
Hello,
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.
Cette question est clôturée.
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!