Info

Questa domanda è chiusa. Riaprila per modificarla o per rispondere.

i wanna improve my function

1 visualizzazione (ultimi 30 giorni)
asaf omer
asaf omer il 2 Lug 2019
Chiuso: MATLAB Answer Bot il 20 Ago 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 Commento
Geoff Hayes
Geoff Hayes il 2 Lug 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.

Risposte (1)

infinity
infinity il 2 Lug 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.

Questa domanda è chiusa.

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by