# A way to write "if x is in y matrix do this"

1 ビュー (過去 30 日間)
Jake 2023 年 1 月 30 日

so long story short im attempting to create a random value and then see if the value is in one range of numbers or another.
ive been able to do the randomising numbers part and tried to use the "ismember" function in the form:
if ismember(y,x)
im pretty certain this is the part of the code that is stopping me from getting the answers i want but cant find anything to solve it

サインインしてコメントする。

### 採用された回答

Star Strider 2023 年 1 月 30 日
It depends what the random number is, and how you define ‘y’ . The ismember function works for exact comparisons. The ismembertol function allows tolerances, and so is suitable for floating-point numbers.
Also, it may be necessary to use the any function with the result —
y = 1:10;
x = randi(20,1)
x = 8
im = ismember(y,x)
im = 1×10 logical array
0 0 0 0 0 0 0 1 0 0
Lany = any(im)
Lany = logical
1
Lall = all(im)
Lall = logical
0
Experiment to get the result you want.
.

サインインしてコメントする。

### その他の回答 (1 件)

John D'Errico 2023 年 1 月 30 日

You CANNOT use ismember to test if a number is in an interval. Even ismembertol does not do that. Using code to do something it is not programmed to do tends to result in failures.
Can you test to see if a number lies in some interval? OF COURSE!!!!!!! That part is trivial.
intervaltest = @(x,lb,ub) (x>=lb) & (x<=ub);
x = rand(1,6)
x = 1×6
0.3244 0.9485 0.5797 0.5892 0.3590 0.6527
intervaltest(x,.3,.6)
ans = 1×6 logical array
1 0 1 1 1 0
So points 1,3,4,5 were in the interval, and points 2 and 6 were not.

サインインしてコメントする。

### カテゴリ

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

R2022b

### Community Treasure Hunt

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

Start Hunting!

Translated by