2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【MATLAB】構造体配列から任意のフィールドのみを抽出した配列を作成する

Last updated at Posted at 2025-12-29

背景

構造体は、フィールドと呼ばれるデータコンテナを使用して、ひとつの変数に複数のデータを格納するデータ型です。例えば、data.Time, data.Position, data.Velocity, のように、シミュレーションや実験結果を構造体として扱う人も少なくないと思います。
ただし、シミュレーションや実験において、こういったデータは時系列データとして取得および保存することが一般的で、その際には構造体配列とする人も多いのではないでしょうか。

サンプルデータ作成
Data = struct('Time',{0,1,2,3,4,5}, ...
              'Position',{10,11,12,13,14,15}, ...
              'Velocity',{1,1,1,1,1,1})

出力

Index Time Position Velocity
1 0 10 1
2 1 11 1
3 2 12 1
4 3 13 1
5 4 14 1
6 5 15 1

困りごと

構造体配列を可視化しようとしたとき、線が引かれない…。

plot
plot(Data.Time, Data.Position)

何が起きている?

とりあえず、まずはplot関数に渡した変数がどうなっているかチェック

Check
Data.Position

出力
ans = 10
ans = 11
ans = 12
ans = 13
ans = 14
ans = 15

この書き方では、配列ではなく複数個のスカラーとして出力がされるよう。
つまり、(0,10)または(5,15)の一点のみがplotされたと推測。

ちなみに、Data(:).PositionData(1:6).Positionでも結果は同じ

なので、何らかの配列となる形でDataのフィールドを抽出できればplotできるはず!

結論

この書き方でいい感じになる

解決方法
plot([Data.Time], [Data.Position])

何らかの考察

実は、インデックスごとに処理および出力がされるような書き方として、同じ再現方法がある。

別の再現方法
1,2,3,4,5

出力
ans = 1
ans = 2
ans = 3
ans = 4
ans = 5

つまり、Data.Positionとしても、10, 11, 12, 13, 14, 15というような出力がされていると推測できる。なので、[1,2,3,4,5]が配列として出力されるように、[Data.Position]も配列として出力されると考えられる。

再確認
[Data.Position]

出力
ans = 1×6
10 11 12 13 14 15

余談(供養)

struct2tableで構造体配列をTableに変換してもいい模様。
でも[Data.Position]の方が楽そうなのでボツ…。

テーブル変換
struct2table(Data)

出力
ans = 6×3 table

Time Position Velocity
0 10 1
1 11 1
2 12 1
3 13 1
4 14 1
5 15 1
フィールド名もいっぺんに
struct2table(Data).Position

出力
ans = 6×1
10
11
12
13
14
15

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?