Mathematica Asked by Leslie Chiu on April 4, 2021
Say I generate a set of 20 random numbers by x=RandomReal[{0, 1}, 20], I want to compare every element of x with 0.4. If it is less than or equal to 0.4, then return 1; if it is greater than 0.4, then return 0. Seems "If" does not work on this problem. Thanks.
SeedRandom[1]
x = RandomReal[{0, 1}, 20];
t = .4;
You can also use UnitStep
or Boole
or Clip
as follows:
result1 = UnitStep[t - x];
result2 = Boole[# <= t] & /@ x;
result3 = Round @ Clip[x, {t, t}, {1, 0}];
Grid[Prepend[Transpose[{x, result1, result2, result3}],
{"x", "UnitStep[t-x]", "Boole[#≤t]&/@x", "Round@Clip[x, {t,t},{1,0}]"}],
Dividers -> All]
Correct answer by kglr on April 4, 2021
Try Map[(If[# <= 0.4, 1, 0]) &, RandomReal[{0, 1}, 20]]
!
Answered by Florian Hamamelis on April 4, 2021
@LeslieChiu
Follow @kglr suggestion
Clear["`*"];
f[x_] = Piecewise[{{1, x <= 0.4}, {2, 0.4 < x <= 0.7}, {3,
0.7 < x <= 1}}];
f /@ RandomReal[{0, 1}, 20]
Answered by cvgmt on April 4, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP