Main Content

Web サービスからのデータの変換

この例では、Web サービスからデータをダウンロードして、webread で関数をコンテンツ リーダーとして使用する方法を説明します。

国立地球物理データ センター (NGDC) は、Web サービスを通してさまざまな地球物理データおよび宇宙天気データを提供しています。NGDC は、さまざまなデータセットの中でも、アメリカ変光星観測者協会 (AAVSO) が公開する太陽の黒点数を集計しています。webread を使用して、1945 年以来の各年の黒点数をダウンロードします。

api = 'http://www.ngdc.noaa.gov/stp/space-weather/';
url = [api 'solar-data/solar-indices/sunspot-numbers/' ...
       'american/lists/list_aavso-arssn_yearly.txt'];
spots = webread(url);
whos('spots')
  Name       Size              Bytes  Class    Attributes

  spots      1x1269             2538  char               

NGDC Web サービスは、黒点データをテキストとして返します。既定では、webread はデータを文字配列として返します。

spots(1:100)
ans =

        American
   Year     SSN
    1945    32.3
    1946    99.9
    1947   170.9
    1948   166.6

webread は、データを異なる型として返す関数を使用できます。readtablewebread とともに使用して、黒点データを table として返すことができます。

readtable に関数を指定する weboptions オブジェクトを作成します。

myreadtable = @(filename)readtable(filename,'HeaderLines',1, ...
    'Format','%f%f','Delimiter','space','MultipleDelimsAsOne',1);
options = weboptions('ContentReader',myreadtable);

このデータに対して、readtable をいくつかの Name,Value 入力引数で呼び出して、データを変換します。たとえば、Format は各行に 2 つの数字があることを示します。スペースは区切り記号で、複数の連続するスペースは単独の区切り記号として扱われます。これらの入力引数で readtable を呼び出すには、readtable と引数を新しい関数 myreadtable でラップします。myreadtable をコンテンツ リーダーとして、weboptions オブジェクトを作成します。

黒点データをダウンロードして、データをテーブルとして返します。

spots = webread(url,options);
whos('spots')
  Name        Size            Bytes  Class    Attributes

  spots      76x2              2932  table              

列と行ごとに黒点データを表示します。

spots(1:4,{'Year','SSN'})
ans = 

    Year     SSN 
    ____    _____

    1945     32.3
    1946     99.9
    1947    170.9
    1948    166.6

年ごとの黒点数をプロットします。テーブル関数を使用して、2013 年までの黒点数を選択します。YearSSN の列を配列に変換してプロットします。

rows = spots.Year < 2014;
vars = {'Year','SSN'};
spots = spots(rows,vars);
year = spots.Year;
numspots = spots.SSN;
figure
plot(year,numspots);
title('Sunspot Data');
xlabel('Year');
ylabel('Number of Sunspots');
xlim([1940 2015])
ylim([0 180])

Sunspot data plotted as the number of sunspots by year

集計データと Web サービスは NGDC から提供されています。黒点データは AAVSO から提供されています (最初の公開は、AAVSO Sunspot Counts: 1943-2013, AAVSO Solar Section (R. Howe, Chair) です)。