1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

論理配列で要素を抽出する

Posted at

課題:あるベクトルから特定の要素を抜き出したい

例:
v = [1,2,3,4,5]
から
[1,3,4]
だけ抜き出したい.

解決法:logicalで論理配列を作成して,要素を制御する

方法:

  1. 論理配列のもとになる0/1で構成されるベクトルを作成する
  2. logical関数で論理配列に変換する
  3. ベクトルに適用する
logical_mask.m
>> v = 1:10
v =
     1     2     3     4     5     6     7     8     9    10

>> mask = [1,0,1,1,0]
mask =
     1     0     1     1     0

>> mask = horzcat(mask,mask)
mask =
     1     0     1     1     0     1     0     1     1     0

>> logical_mask = logical(mask)
logical_mask =
     1     0     1     1     0     1     0     1     1     0

>> v(mask)
Subscript indices must either be real positive integers or logicals.
 
>> v(logical_mask)
ans =
     1     3     4     6     8     9

logicalで論理配列に変換するのがポイント

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?