# Check an entire matrix against each value of another matrix

2 views (last 30 days)
EYKL on 14 Jan 2022
Commented: Jon on 14 Jan 2022
Dear all,
I have the following code;
1. I want to check matrix b against each value of matrix a, and extract values in matrix b based on a condition.
2. The condition when delta 1 == 0, the value of matrix b corresponding to 0 is extracted into c.
However, I am getting an error Index in position 1 exceeds array bounds (must not exceed 1) in the line below. I have 2 questions:
1. Why is this error happening?
2. Is there another way to accomplish this without using loops?
Thank you.
a = [4 3];
b = [1 4.2 5 6 7 3.2];
c = zeros(size(a));
for i = 1:length(a)
delta1(i,:) = abs((b-a(i))/a(i));
for j = 1:length(delta1)
if delta1(i,j) < 0.3
c(i) = b(i,j); % This line
end
end
end

Jon on 14 Jan 2022
Edited: Jon on 14 Jan 2022
If I understand what you are looking for, I think this will do it in a very simple way
c = intersect(a,b)
>> a = [4 3];
b = [1 4 5 6 7 3];
c = intersect(a,b)
c =
3 4
Jon on 14 Jan 2022
You should also check out the MATLAB function ismembertol https://www.mathworks.com/help/matlab/ref/ismembertol.html which is pretty much purpose built for the operation you are trying to perform, but the error tolerance is a little different. If you are comfortable with their way of computing the tolerance you can use this directly

R2020b

### Community Treasure Hunt

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

Start Hunting!