Info

この質問は閉じられています。 編集または回答するには再度開いてください。

Search all elements from from array A in array B and write it workspace

1 回表示 (過去 30 日間)
Santosh Gnanasekar
Santosh Gnanasekar 2019 年 5 月 14 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
Hello All,
Iam trying to code to Search all elements from array A in array B and write it workspace
Array A = [0.012 0.014.... 5.04];
Array B = [0.01 0.36 0.125 0.36 .. 10.04];
my approach
for i = 1: length(Array A)
if Array A(i) = [Array B]
Output = Array A(i);
end
i = i+1;
end
<<This is not working>>
Any support would be great.. Thanks
  1 件のコメント
Adam
Adam 2019 年 5 月 14 日
It would help if you just post actual code. 'Array A' clearly is not a valid variable name.
You would also do well to read the basic Matlab help on for loops
doc for
i = 1:length( A )
will already iterate through your for loop so adding
i = i + 1;
is not required.
Also
if Array A(i) = [Array B]
is wrong/invalid in every way possible:
  • Putting [ ] around a variable is un-necessary
  • = is an assignment operator. == is a comparison operator
  • A(i) == B would give you an array of results so you wouldn't want to put this in an if statement
  • You shouldn't use the equality operator at all on floating point data due to inaccuracies in the way such data is stored. Testing equality within a tolerance is almost always better.
doc ismembertol
will help you with this if you are using R2015a or later.

回答 (2 件)

Raj
Raj 2019 年 5 月 14 日
編集済み: Raj 2019 年 5 月 14 日
Your thinking is basically correct.
for i = 1: length(Array A) % Start with first element of A
if Array A(i) = [Array B] % compare each element of A (one at a time) with all elements of B
Output = Array A(i); % if match found then write it as Output in workspace
end
i = i+1; % increment index for A
end
However there are many syntax errors. Use this:
for i=1:numel(A)
for j=1:numel(B)
if A(i)==B(j)
output(i)=A(i);
end
end
end
output=output(output ~= 0)
Recommend going through some basic MATLAB tutorials.

Andrei Bobrov
Andrei Bobrov 2019 年 5 月 14 日
Output = A(ismember(A,B))

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by