Using find to determine equality not of scalars, but vectors
4 ビュー (過去 30 日間)
古いコメントを表示
Hi, I have two vectors say x=[1 2 3 4 5 ] and y=[2 4].
I would like to find the elements of y in x. Usually, if y is a scalar, a simple find(x==2) would do teh trick, or even x(x==2).
Is there something similar that would work like find(x==y) or x(x==y), without using a loop?
0 件のコメント
回答 (2 件)
John D'Errico
2023 年 5 月 26 日
編集済み: John D'Errico
2023 年 5 月 26 日
This is not really the province of find. Yes, you can break an egg with a hammer, but it is not really the right tool for the purpose. (Ok, yes, the scrambled eggs made that way will be high in fiber. But they tend to be a little too crunchy for my tastes.) Instead, you need to learn about the set membership tools in MATLAB.
First, I'll make the problem slightly more interesting, since using the numbers 1:5 may confuse things.
x=[1:3:21]
y=[2:2:20]
There are clearly some elements in y that are not in x, and vice versa.
help ismember
[yinx,xloc] = ismember(y,x)
So which elements of y were found in x?
y(yinx)
That makes sense. Next, where were they found?
xloc(yinx)
So at locations [2,4,6] in the x vector.
You will also find the setdiff tool to be useful at times, as well as intersect and union. Spend some time familiarizing yourself with many of these fundamental tools in MATLAB. It will be well worth the time invested.
1 件のコメント
Stephen23
2023 年 5 月 26 日
And here are all of the basic set functions:
Note the contents on the LHS of the page: learn to navigate this so that you can find information by yourself.
Harsh Mahalwar
2023 年 5 月 26 日
編集済み: Harsh Mahalwar
2023 年 5 月 26 日
Hi Josue,
You can use the following matlab script to find the elements of y in x without using a loop.
y = [2 4];
x = [1 2 3 4 5];
findLoc = arrayfun(@(i) find(x==i,1),y);
Here are some references,
Thanks and regards,
Harsh Mahalwar
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!