Check an entire matrix against each value of another matrix

11 次查看(过去 30 天)
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
Jon 2022-1-14
编辑:Jon 2022-1-14
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
  5 个评论
Jon
Jon 2022-1-14
编辑:Jon 2022-1-14
Ooops, that last line should be
c = b(any(delta < 0.3))
c =
4.2000 5.0000 3.2000
if you want to list the values that match out of b instead of the ones out of a (as in code above)
Jon
Jon 2022-1-14
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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by