Check an entire matrix against each value of another matrix

13 ビュー (過去 30 日間)
EYKL
EYKL 2022 年 1 月 14 日
コメント済み: Jon 2022 年 1 月 14 日
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 Center および File ExchangeLogical についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by