How do I compare the elements of two vectors 1 by 1?

46 ビュー (過去 30 日間)
Tyler Johnson
Tyler Johnson 2016 年 9 月 7 日
回答済み: Star Strider 2016 年 9 月 7 日
I am trying to manually write a set intersection function in matlab. I need to compare all of the elements of each vector. Right now for the comparison I have an for loop with an if statement inside:
for i = 1:length(uset1)
if uset1(i) == uset2(i)
result = i;
uset1 and uset2 are single row vectors where no elements are duplicated. Whenever I try to run I get an error saying that '==' is an undefined operator for input arguments of type 'cell'. Is there another way to compare individual elements of two vectors?

回答 (2 件)

Azzi Abdelmalek
Azzi Abdelmalek 2016 年 9 月 7 日
編集済み: Azzi Abdelmalek 2016 年 9 月 7 日
Use curly brackets
uset1{i} == uset2{i}
You can avoid for loop
out=find(cellfun(@(x,y) x==y,uset1,uset2))

Star Strider
Star Strider 2016 年 9 月 7 日
Another approach:
uset1 = {randi(9, 1, 20)}; % Create Data
uset2 = {randi(9, 1, 20)}; % Create Data
LV = cellfun(@ne, uset1, uset2, 'Uni',0); % Logical Vector
out = find(~LV{:}); % Indices Of Equal Elements

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by