Replace odd numbers with infinity

8 ビュー (過去 30 日間)
timetry2
timetry2 2019 年 10 月 12 日
コメント済み: timetry2 2019 年 10 月 13 日
I have a code that looks like the following:
C = randi([100,200],1000,1000);
evenIndices = rem(C,2) == 0
allTheEvenNumbers = C(evenIndices)
allTheEvenNumbers = allTheEvenNumbers -1
locations = find(allTheEvenNumbers)
C(locations) = Inf
I am wanting the odd numbers to be replaced by Inf but it is not working. Where am I going wrong?
  2 件のコメント
Adam Danz
Adam Danz 2019 年 10 月 12 日
per isakson
per isakson 2019 年 10 月 13 日
編集済み: per isakson 2019 年 10 月 13 日
@Adam Thanks, I missed that.

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

採用された回答

per isakson
per isakson 2019 年 10 月 12 日
編集済み: per isakson 2019 年 10 月 13 日
%%
C = randi([100,200],3,6)
is_odd = rem(C,2) == 1;
D = C;
D( is_odd ) = inf
returns
C =
117 103 107 159 122 113
137 199 184 123 152 191
134 152 158 145 188 133
D =
Inf Inf Inf Inf 122 Inf
Inf Inf 184 Inf 152 Inf
134 152 158 Inf 188 Inf
which looks ok.
"Where am I going wrong?"
  • The title says "Replace odd ..." and the code focuses on even
  • experimenting with a large matrix, which is difficult to inspect
  • evenIndices is a logical index, in which true indicates locations with even values. evenIndices is not an optimal name.
  • allTheEvenNumbers is a vector of integers in the range of [ 100, 200 ]. The number of elements in allTheEvenNumbers is approximately half of that in C.
  • it is not meaningsful to substract one from allTheEvenNumbers. Ok, is your intention a negation of a logical value?
  • ...
In response to a comment
In the previous question, there is a requirement to use the function, find()
One may do that, but there is little point
%%
C = randi([100,200],3,6)
C( find( rem(C,2) == 1 ) ) = inf
returns
C =
180 103 168 139 171 104
196 185 176 166 103 109
166 194 175 117 127 183
C =
180 Inf 168 Inf Inf 104
196 Inf 176 166 Inf Inf
166 194 Inf Inf Inf Inf
  1 件のコメント
timetry2
timetry2 2019 年 10 月 13 日
Thank you so much! This really helped

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by