MATLABのコードって忘れやすい・・・

プログラムのコマンドなんて忘れやすいもの・・・いっそのことネット上に保存してシェアしましょう!!
It's easy to forget command for MATLAB in programming.... Let's share small help for Matlab code with you on the web!!



2010年9月30日木曜日

棒グラフ色々 Several bar graphs

Y = round(rand(5,3)*10);
subplot(2,2,1)
bar(Y,'grouped')
title 'Group'
subplot(2,2,2)
bar(Y,'stacked')
title 'Stack'
subplot(2,2,3)
barh(Y,'stacked')
title 'Stack'
subplot(2,2,4)
bar(Y,1.5)
title 'Width = 1.5'

2010年9月24日金曜日

軸の設定 Axis setting

・軸の反転
set(gca,'XDir','rev','YDir','rev','ZDir','rev')
・軸の範囲
set(axes_handle,'XLim',[0 100])
・軸の目盛
set(gca,'YTick',[0 0.05 0.075 0.1 0.15 0.2 0.25])


詳細はこちら

2010年9月21日火曜日

matrixの上下の反転 Flip a matrix from up to bottom

使えそうなコードを見つけた・・・flipud
matrixをup & downと反転させる場合に使えそう。

function y = flipud(x)
%FLIPUD Flip matrix in up/down direction.
% FLIPUD(X) returns X with columns preserved and rows flipped
% in the up/down direction. For example,
%
% X = 1 4 becomes 3 6
% 2 5 2 5
% 3 6 1 4
%
% Class support for input X:
% float: double, single
%
% See also FLIPLR, ROT90, FLIPDIM.

% Copyright 1984-2004 The MathWorks, Inc.
% $Revision: 5.9.4.3 $ $Date: 2004/07/05 17:01:15 $

if ndims(x)~=2
error('MATLAB:flipud:SizeX', 'X must be a 2-D matrix.');
end
y = x(end:-1:1,:);

errorbar etc....

Matlab Centralを見ると、errorbarに関するコードが他にもこんなにあった。

http://www.mathworks.com/matlabcentral/fileexchange/27387-create-healthy-looking-error-bars

http://www.mathworks.com/matlabcentral/fileexchange/10803-barweb-bargraph-with-error-bars

http://www.mathworks.com/matlabcentral/fileexchange/27494

ってなわけで、これを試してみるべし。

paired t-test

[h1,p1]=ttest2(X,Y,0.05,'both','unequal')

h1=1ならベクトルX,Yに有意に差がある。
h0=0ならベクトルX,Yにp1の確率で差がない。

bar + errorbar

http://www.mathworks.co.jp/support/solutions/ja/data/1-9J8S0T/index.html?product=ML&solution=1-9J8S0Tより抜粋。

BAR 関数で棒グラフを描画し、ハンドルから棒グラフの左端と右端の X 座標を取得して中心値を計算し、中心値に対して ERRORBAR 関数で描画します。
具体的には、下記の手順で行なえます。

1. bar 関数で棒グラフを描画(このとき、出力引数を付けてハンドルを取得)
2. 上記 1 で得られたハンドル各棒グラフの X 座標値を取得し、各棒グラフの
   中心座標を計算
3. 上記 2 で計算した X 座標を使用し、 errorbar 関数でエラーバーを描画

以下に例を示します。

% データ定義
Y = round(rand(5,3)*10); % グループ数 3、標本数 5
e = std(Y); % 標準偏差の計算

% 棒グラフの描画
figure, h = bar(Y,'hist'); % ハンドルを取得
hold on

[numgroups, numbars] = size(Y); % numgroups: グループ数, numbars: 標本数

% 各棒グラフのX座標値を取得
xdata = get(h,'XData'); % 出力はセル配列
% X座標から各棒グラフの中心座標を計算
centerX = cellfun(@(x)(x(1,:)+x(3,:))/2,xdata,'UniformOutput', false);

E = repmat(e,numgroups,1); % グラフ表示用にデータを拡張
C = {'b','g','r'}; % エラーバーの色

% 標準偏差を棒グラフに重ねて描画
for i = 1:numbars
errorbar(centerX{i,:}, Y(:,i), E(:,i), C{i},...
'linestyle', 'none','LineWidth',2);
end

なお、このプログラムでは、グループ毎に標準偏差の色分けを行い、さらに ERRORBAR 関数の各点を結ぶ線を非表示にしてプロットしています。
各点を結ぶ線を消すには、出力引数を付けて ERRORBAR 関数を実行後、'LineStyle' プロパティに 'None' を設定します。

また、プログラム内では、各棒グラフの X座標の中心座標を計算する際に、CELLFUN 関数を使用しています。この関数の機能については、関連ソリューションをご覧下さい。