SlideShare uma empresa Scribd logo
1 de 47
Baixar para ler offline
Good Coding For Research
       -MATLAB ‘GOOD’ Script-
       K. Harada(@sousoumt)自己紹介略




12年11月26日月曜日                       1
読者前提


               MATLABを使用している

               コードの書き方について学んだ経験がない



                       原田注:資料内では「研究のために」とありますが、
                    研究者以外でも役に立つよう汎用的な資料にしているつもりです。
                        それぞれ「∼のために」を読み替えてください。
12年11月26日月曜日                                         2
良いコードを書こう




12年11月26日月曜日       3
充実した研究のために
       良いコードを書こう



12年11月26日月曜日        4
無駄はないか?

12年11月26日月曜日     5
無駄なコーディングしていませんか?

               無駄なチュートリアルしていませんか?




12年11月26日月曜日                        6
チュートリアルにおける理想

       •教える側
           •コード見てね!とだけ伝えたい。    コードの読みやすさが重要!
                               「動けば良い」は全然ダメ
       •教わる側
           •より短時間でより正確に知りたい。



12年11月26日月曜日                                   7
コードの可読性を高める

12年11月26日月曜日         8
良いコード≒可読性が高い




12年11月26日月曜日          9
やっつけで可読性の低いコードを書く

                  コード内に情報が不足

                  バグ発見時修正が困難

                 コード改良に時間を要する

                  研究に割く時間が減る

                  研究の質が低下する


12年11月26日月曜日                       10
整理された可読性の高いコードを書く

                  コード内に情報が足る

                  バグ発見時修正が容易

                 コード改良が短時間で済む

                  研究に割く時間が増える

                  研究の質が向上する


12年11月26日月曜日                       11
可読性の高いコードを書き
       研究に時間を使おう



12年11月26日月曜日          12
Good Coding For Research
       -MATLAB ‘GOOD’ Script-
       K. Harada




12年11月26日月曜日                      13
スクリプトと関数を切り分ける

               登場順を意識する

               名前に情報を詰め込む

               コメントを大事に使う

               ゴミを残さない




12年11月26日月曜日                    14
スクリプトと関数を切り分ける

               登場順を意識する

               名前に情報を詰め込む

               コメントを大事に使う

               ゴミを残さない




12年11月26日月曜日                    15
スクリプトと関数を切り分ける

               実行可能?ファイル名で区別する

               大枠から書く

               関数にはin-outの記述を

               スクリプトの究極は一読可能!

               さらに切り分ける
                         原田注:以降の資料では、左が悪い例、右が良い例として記載しています。


12年11月26日月曜日                                                  16
実行可能?ファイル名で区別する

                convertNsn2Mat2.m      convertNsn2Mat_BATCH.m
                 convertNsn2Mat.m          convertNsn2Mat.m




               convertNsn2Mat_func.m
                      convert.m



12年11月26日月曜日                                                    17
大枠から書く


               処理1               % 処理1
                                 % 処理2 % 処理1

                     処理1         % 処理3 処理1
                                                 % 処理1
                     処理2                 % 処理2
                                                 処理1
                           処理1           % 処理3
                                                 % 処理2
                           処理2
                                                 処理2
                           処理3
                                                 % 処理3

12年11月26日月曜日                                             18
関数にはin-outの記述を

   som_train_with_scale_parameter.m     function [w w_matrix] =
                                        som_train_with_scale_parameter(
        function [w w_matrix] =         data_matrix, num_cell, N_0)
        som_train_with_scale_parameter( % Train with scale parameters.
        data_matrix, num_cell, N_0)      % Input:
                                         % data_matrix - ****
                                         % num_cell     - ****
                                         % N_0          - ****
              コメント何もなし                   % Output:
                                         % w              - ****
                                         % w_matrix     - ****

12年11月26日月曜日                                                              19
スクリプトの究極は一読可能!
           for i=1:10
             for j=1:20                       runs = 1:10;
               if data{i,j}~=NaN              channels = 1:20;
                 if D.label{j} ~= P.Num{i}
                   fprintf(‘num ne label’);   % Check Values
                   :                          if ~checkArgs(runs, channels, D, P)
                 else if D.roi{j} == NaN        error(‘format error.’);
                   error(‘roi not found’);    end
                 end
               end
             end ロジック解読が必要                           ロジック解読が不要
           end

12年11月26日月曜日                                                                        20
さらに切り分ける

               convertNsn2Mat_BATCH.m   convertNsn2Mat_BATCH.m
          calc***                       calc***
          :                             :
          gca                           showGraph;
          xlabel(***);                      _BATCHには本質が残る
          ylabel($$$);
                                        showGraph.m
                           gca
        _BATCHに読み飛ばせる部分がある xlabel(***);
                           ylabel($$$);

12年11月26日月曜日                                                     21
スクリプトと関数を切り分ける

               登場順を意識する

               名前に情報を詰め込む

               コメントを大事に使う

               ゴミを残さない




12年11月26日月曜日                    22
登場順を意識する

               先頭の情報は最も大事

               混ぜるな危険!スクラッチブルに

               終わったのか?done出力

               更新は誰が?いつ?日付とauthor




12年11月26日月曜日                        23
先頭の情報は最も大事

          convertMat2Nsn_BATCH.m         convertMat2Nsn_BATCH.m
         %function [w w_matrix] =        %   Convert Mat to Nsn file.
           convertMat2Nsn(               %   1 : check Mat file existing
           data_matrix, num_cell, N_0)   %   2 : check Mat format.
                                         %   3 : convert.
         if exist(‘abc.mat’)
         :        スクリプト?関数?
         end
                  引数に必要なもの?
                                              続きの内容を容易に追える
                clearが無かったら?

12年11月26日月曜日                                                              24
混ぜるな危険!スクラッチブルに
                                              num=5
         for kk=1:20
                                              kkMax=20
           data=load([‘svsv/fmri/data/’ kk]);
           resA{kk}=calcA(data);
                                              for kk=1:kkMax
         end
                                                data=load([‘sv/fmri/data/’ kk]);
                                                resA{kk}=calcA(data);
         num = 5;
                                              end
         calcB(resA,num);
                                              calcB(resA,num);

               処理とパラメータが混在                           処理とパラメータが別


12年11月26日月曜日                                                                       25
終わったのか? done出力

        num=5                                num=5
        kkMax=20                             kkMax=20

        for kk=1:kkMax                       for kk=1:kkMax
          data=load([‘sv/fmri/data/’ kk]);     data=load([‘sv/fmri/data/’ kk]);
          resA{kk}=calcA(data);                resA{kk}=calcA(data);
        end                                  end
        calcB(resA,num);                     calcB(resA,num);
                                             fprintf(‘%s Donen’, mfilename);
               終わったのか不明                         Doneと出力されたら終了
                                                     mfilenameも有効

12年11月26日月曜日                                                                      26
更新は誰が?いつ?日付とauthor
                                    % Do abc
        % Do abc                    % 1 : check inputs.
        % 1 : check inputs.         % 2 : execute abc.
        % 2 : execute abc.          % Modified By: K*** Harada
                                    kharada at ****.co.jp 12/09/26
        if ~checkArgs(abc)
          error(‘’);                if ~checkArgs(abc)
        end                           error(‘’);
        exec(abc);                  end
                                    exec(abc);

           いざという時誰に聞けば?             最も良く知る人が把握可能


12年11月26日月曜日                                                         27
スクリプトと関数を切り分ける

               登場順を意識する

               名前に情報を詰め込む

               コメントを大事に使う

               ゴミを残さない




12年11月26日月曜日                    28
名前に情報を詰め込む

               名前だけでバグを防ぐ

               スコープの意識

               難しく考えないで命名規則

               tempは誰も喜ばない




12年11月26日月曜日                  29
名前だけでバグを防ぐ
                                                    for row = 1:10
        for ii = 1:10                                 for col = row:20
          for jj = ii:20                                if matrix{row, col} ~=NaN
            if matrix{ii,jj} ~=NaN                        oneData = 6*data{row, col};
              calcB(6*data{ii,jj}, label{ii,ii});         oneLabel = label{row, row};
            end                                           calcB(oneData,oneLabel);
          end                                           end
        end                                           end
                                                              意味のある変数名は
                                                    end
                                                              バグに気付きやすい
               意味のない変数名は
                                                    単数名or複数名の使い分けも良い
               バグに気付きにくい

12年11月26日月曜日                                                                            30
スコープの意識
       for rowCounter = 1:10            for rowCounter = 1:10
         for colCounter = rowCounter:20 for colCounter = rowCounter:20
           if ~exist(temp)                 if ~exist(temp)
             temp = data{rowC,colC};         temp = data{rowC,colC};
           end                             end
         end                              end
       end                              end
                                         別の処理部分に影響させない
                                        clear temp;
       別の処理部分に影響する可能性
       for temp=1:20                    for temp=1:20
         showNanika;                      showNanika;
       end                              end

12年11月26日月曜日                                                             31
難しく考えないで命名規則




           similaritymatrix
           SIMILARITYMATRIX    similarityMatrix : 変数
           SimilarityMatrix    SIMILARITY_MATRIX : 定数
           similarity_matrix   SimilarityMatrix : クラス
           sm
                                   これ以外であっても、
                               ソース内で統一されていれば可
                               変数名の長さ∝変数のスコープ

12年11月26日月曜日                                            32
tempは誰も喜ばない



                             calcB(calcA());

                             or
           temp = calcA();
           calcB(temp);
                             resultCalcA = calcA();
             何が入っているのか?      calcB(resultCalcA);
               再利用されるのか?     clear resultCalcA;
                   要追跡                   追跡不要



12年11月26日月曜日                                          33
スクリプトと関数を切り分ける

               登場順を意識する

               名前に情報を詰め込む

               コメントを大事に使う

               ゴミを残さない




12年11月26日月曜日                    34
コメントを大事に使う

               鉄は熱いうちに、コメントは覚えているうちに

               重要なことを足す

               疑問、質問、こうなったらバグだ!も書く

               パラメータだけコメント化が許される

               %%は部分処理と現在地確認に用いる



12年11月26日月曜日                           35
鉄は熱いうちに、コメントは覚えているうちに
                               % Parameters
          % Parameters         A = [1 2 3];
          A = [1 2 3];
                             % do X
         % do X              resultX = execX(A);
         resultX = execX(A); % Test from
         resultX = execY(A); resultX = execY(A);
                             % Test to
         % do B                    インラインでもOK
         execB(resultX);     % do B
         食事後すぐ元通りにできるか? execB(resultX);


12年11月26日月曜日                                       36
重要なことを足す


                                     % Parameters
               % Define Parameter A
                                     A = [1 2 3];
               A = [1 2 3];
                                     % do X
               resultX = execX(A);
                                     resultX = execX(A);
               % execB
                                     % do B
               execB(resultX);
                                     execB(resultX);
         見て分かることを書いてしまう                     コメントだけで
                必要なことが抜けている                 コードが読める

12年11月26日月曜日                                               37
疑問、質問、こうなったらバグだ!も書く
                                % Parameters
          % Parameters          A = [1 2 3];
          A = [1 2 3];
                                % do X
          % do X                resultX = execX(A);
          resultX = execX(A);   % execX失敗時は?
                                % A未定義時はエラー発生
          % do B
          execB(resultX);
                                % do B
                 execX失敗時は?     execB(resultX);
                                      気付きを記載


12年11月26日月曜日                                          38
パラメータだけコメント化が許される


          % Parameters                  % Parameters
          A = [1 2 3];                  A = [1 2 3];
          A = {[1 2 3]; [2]; [3]};      % A = {[1 2 3]; [2]; [3]}; %multiple
                                        case
          % do X
          resultX = execX(A);           % do X
          %resultX = execY(A); % Cell   resultX = execX(A);

               死んでいるパラメータ               設定可能なパラメータを示す
                処理内容にコメント 処理内容はパラメータにだけ依存させる

12年11月26日月曜日                                                                   39
%% は部分処理と現在地確認に用いる



            % Parameters                 %% Parameters
            A = [1 2 3];                 A = [1 2 3];
            % A = {[1 2 3]; [2]; [3]};   % A = {[1 2 3]; [2]; [3]};

            % do X                       %% do X
            resultX = execX(A);          resultX = execX(A);

               パラメータの設定確認など              パラメータの設定確認他
                 部分処理ができない                     部分処理が可能
           今どの部分の処理を実行中?                   「現在地」を把握可能
12年11月26日月曜日                                                          40
スクリプトと関数を切り分ける

               登場順を意識する

               名前に情報を詰め込む

               コメントを大事に使う

               ゴミを残さない




12年11月26日月曜日                    41
ゴミを残さない

               変数一覧には重要性の表記がない

               一時的変数は即消し

               スクリプトが出力の責任を持つ

               未使用コードはVCSで積極的に消す




12年11月26日月曜日                       42
変数一覧には重要性の表記がない



               実行後のWorkspace

               ii double 8         実行後のWorkspace
               jj double 55
               matrix cell         matrix cell
               resultX double 1
               a logical true
                                       必要な結果のみを残す
                    必要な結果は何?
                                     saveで全変数の保存も有効

12年11月26日月曜日                                          43
一時的変数は即消し




                                    [temp data] = calcA();
           [temp data] = calcA();
                                    calcB(data);
           calcB(data);
                                    clear temp;




                    tempは残る             tempは残らない


12年11月26日月曜日                                                 44
スクリプトが出力の責任を持つ

           %% Parameters               close all;
           A = [1 2 3];                clear;

           execX(A)                    %% Parameters
                                       A = [1 2 3];
           [temp data] = calcA();      :
           ww = fopen(‘test.txt’);
           calcB(data);                close all;
           fclose(ww);                 clear;
               calcBでエラー&中止時は?       初期化操作close all;clear;で
                                        出力に責任を持つ
12年11月26日月曜日                                                  45
未使用コードはVCSで積極的に消す


            % Parameters
            A = [1 2 3];                 % Parameters
            % A = {[1 2 3]; [2]; [3]};   A = [1 2 3];
                                         % A = {[1 2 3]; [2]; [3]};
            % do X
            resultX = execX(A);          % do X
            %resultX = execY(A);         resultX = execX(A);
            %resultX = execZ(A);
                 コメントインすると                    必要な処理のみ残す
                  すぐ使えてしまう                VCSを使えばすぐ確認可能

12年11月26日月曜日                                                          46
まとめ

               スクリプトと関数を切り分ける

               登場順を意識する

               名前に情報を詰め込む

               コメントを大事に使う

               ゴミを残さない



12年11月26日月曜日                    47

Mais conteúdo relacionado

Último

東京工業大学 環境・社会理工学院 建築学系 大学院入学入試・進学説明会2024_v2
東京工業大学 環境・社会理工学院 建築学系 大学院入学入試・進学説明会2024_v2東京工業大学 環境・社会理工学院 建築学系 大学院入学入試・進学説明会2024_v2
東京工業大学 環境・社会理工学院 建築学系 大学院入学入試・進学説明会2024_v2Tokyo Institute of Technology
 
ゲーム理論 BASIC 演習106 -価格の交渉ゲーム-#ゲーム理論 #gametheory #数学
ゲーム理論 BASIC 演習106 -価格の交渉ゲーム-#ゲーム理論 #gametheory #数学ゲーム理論 BASIC 演習106 -価格の交渉ゲーム-#ゲーム理論 #gametheory #数学
ゲーム理論 BASIC 演習106 -価格の交渉ゲーム-#ゲーム理論 #gametheory #数学ssusere0a682
 
世界を変えるクレーンを生み出そう! 高知エンジニアリングキャンプ2024プログラム
世界を変えるクレーンを生み出そう! 高知エンジニアリングキャンプ2024プログラム世界を変えるクレーンを生み出そう! 高知エンジニアリングキャンプ2024プログラム
世界を変えるクレーンを生み出そう! 高知エンジニアリングキャンプ2024プログラムKochi Eng Camp
 
2024年度 東京工業大学 工学院 機械系 大学院 修士課程 入試 説明会 資料
2024年度 東京工業大学 工学院 機械系 大学院 修士課程 入試 説明会 資料2024年度 東京工業大学 工学院 機械系 大学院 修士課程 入試 説明会 資料
2024年度 東京工業大学 工学院 機械系 大学院 修士課程 入試 説明会 資料Tokyo Institute of Technology
 
生成AIの回答内容の修正を課題としたレポートについて:お茶の水女子大学「授業・研究における生成系AIの活用事例」での講演資料
生成AIの回答内容の修正を課題としたレポートについて:お茶の水女子大学「授業・研究における生成系AIの活用事例」での講演資料生成AIの回答内容の修正を課題としたレポートについて:お茶の水女子大学「授業・研究における生成系AIの活用事例」での講演資料
生成AIの回答内容の修正を課題としたレポートについて:お茶の水女子大学「授業・研究における生成系AIの活用事例」での講演資料Takayuki Itoh
 
次世代機の製品コンセプトを描く ~未来の機械を創造してみよう~
次世代機の製品コンセプトを描く ~未来の機械を創造してみよう~次世代機の製品コンセプトを描く ~未来の機械を創造してみよう~
次世代機の製品コンセプトを描く ~未来の機械を創造してみよう~Kochi Eng Camp
 

Último (6)

東京工業大学 環境・社会理工学院 建築学系 大学院入学入試・進学説明会2024_v2
東京工業大学 環境・社会理工学院 建築学系 大学院入学入試・進学説明会2024_v2東京工業大学 環境・社会理工学院 建築学系 大学院入学入試・進学説明会2024_v2
東京工業大学 環境・社会理工学院 建築学系 大学院入学入試・進学説明会2024_v2
 
ゲーム理論 BASIC 演習106 -価格の交渉ゲーム-#ゲーム理論 #gametheory #数学
ゲーム理論 BASIC 演習106 -価格の交渉ゲーム-#ゲーム理論 #gametheory #数学ゲーム理論 BASIC 演習106 -価格の交渉ゲーム-#ゲーム理論 #gametheory #数学
ゲーム理論 BASIC 演習106 -価格の交渉ゲーム-#ゲーム理論 #gametheory #数学
 
世界を変えるクレーンを生み出そう! 高知エンジニアリングキャンプ2024プログラム
世界を変えるクレーンを生み出そう! 高知エンジニアリングキャンプ2024プログラム世界を変えるクレーンを生み出そう! 高知エンジニアリングキャンプ2024プログラム
世界を変えるクレーンを生み出そう! 高知エンジニアリングキャンプ2024プログラム
 
2024年度 東京工業大学 工学院 機械系 大学院 修士課程 入試 説明会 資料
2024年度 東京工業大学 工学院 機械系 大学院 修士課程 入試 説明会 資料2024年度 東京工業大学 工学院 機械系 大学院 修士課程 入試 説明会 資料
2024年度 東京工業大学 工学院 機械系 大学院 修士課程 入試 説明会 資料
 
生成AIの回答内容の修正を課題としたレポートについて:お茶の水女子大学「授業・研究における生成系AIの活用事例」での講演資料
生成AIの回答内容の修正を課題としたレポートについて:お茶の水女子大学「授業・研究における生成系AIの活用事例」での講演資料生成AIの回答内容の修正を課題としたレポートについて:お茶の水女子大学「授業・研究における生成系AIの活用事例」での講演資料
生成AIの回答内容の修正を課題としたレポートについて:お茶の水女子大学「授業・研究における生成系AIの活用事例」での講演資料
 
次世代機の製品コンセプトを描く ~未来の機械を創造してみよう~
次世代機の製品コンセプトを描く ~未来の機械を創造してみよう~次世代機の製品コンセプトを描く ~未来の機械を創造してみよう~
次世代機の製品コンセプトを描く ~未来の機械を創造してみよう~
 

Destaque

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Destaque (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Good coding for research

  • 1. Good Coding For Research -MATLAB ‘GOOD’ Script- K. Harada(@sousoumt)自己紹介略 12年11月26日月曜日 1
  • 2. 読者前提 MATLABを使用している コードの書き方について学んだ経験がない 原田注:資料内では「研究のために」とありますが、 研究者以外でも役に立つよう汎用的な資料にしているつもりです。 それぞれ「∼のために」を読み替えてください。 12年11月26日月曜日 2
  • 4. 充実した研究のために 良いコードを書こう 12年11月26日月曜日 4
  • 6. 無駄なコーディングしていませんか? 無駄なチュートリアルしていませんか? 12年11月26日月曜日 6
  • 7. チュートリアルにおける理想 •教える側 •コード見てね!とだけ伝えたい。 コードの読みやすさが重要! 「動けば良い」は全然ダメ •教わる側 •より短時間でより正確に知りたい。 12年11月26日月曜日 7
  • 10. やっつけで可読性の低いコードを書く コード内に情報が不足 バグ発見時修正が困難 コード改良に時間を要する 研究に割く時間が減る 研究の質が低下する 12年11月26日月曜日 10
  • 11. 整理された可読性の高いコードを書く コード内に情報が足る バグ発見時修正が容易 コード改良が短時間で済む 研究に割く時間が増える 研究の質が向上する 12年11月26日月曜日 11
  • 12. 可読性の高いコードを書き 研究に時間を使おう 12年11月26日月曜日 12
  • 13. Good Coding For Research -MATLAB ‘GOOD’ Script- K. Harada 12年11月26日月曜日 13
  • 14. スクリプトと関数を切り分ける 登場順を意識する 名前に情報を詰め込む コメントを大事に使う ゴミを残さない 12年11月26日月曜日 14
  • 15. スクリプトと関数を切り分ける 登場順を意識する 名前に情報を詰め込む コメントを大事に使う ゴミを残さない 12年11月26日月曜日 15
  • 16. スクリプトと関数を切り分ける 実行可能?ファイル名で区別する 大枠から書く 関数にはin-outの記述を スクリプトの究極は一読可能! さらに切り分ける 原田注:以降の資料では、左が悪い例、右が良い例として記載しています。 12年11月26日月曜日 16
  • 17. 実行可能?ファイル名で区別する convertNsn2Mat2.m convertNsn2Mat_BATCH.m convertNsn2Mat.m convertNsn2Mat.m convertNsn2Mat_func.m convert.m 12年11月26日月曜日 17
  • 18. 大枠から書く 処理1 % 処理1 % 処理2 % 処理1 処理1 % 処理3 処理1 % 処理1 処理2 % 処理2 処理1 処理1 % 処理3 % 処理2 処理2 処理2 処理3 % 処理3 12年11月26日月曜日 18
  • 19. 関数にはin-outの記述を som_train_with_scale_parameter.m function [w w_matrix] = som_train_with_scale_parameter( function [w w_matrix] = data_matrix, num_cell, N_0) som_train_with_scale_parameter( % Train with scale parameters. data_matrix, num_cell, N_0) % Input: % data_matrix - **** % num_cell - **** % N_0 - **** コメント何もなし % Output: % w - **** % w_matrix - **** 12年11月26日月曜日 19
  • 20. スクリプトの究極は一読可能! for i=1:10 for j=1:20 runs = 1:10; if data{i,j}~=NaN channels = 1:20; if D.label{j} ~= P.Num{i} fprintf(‘num ne label’); % Check Values : if ~checkArgs(runs, channels, D, P) else if D.roi{j} == NaN error(‘format error.’); error(‘roi not found’); end end end end ロジック解読が必要 ロジック解読が不要 end 12年11月26日月曜日 20
  • 21. さらに切り分ける convertNsn2Mat_BATCH.m convertNsn2Mat_BATCH.m calc*** calc*** : : gca showGraph; xlabel(***); _BATCHには本質が残る ylabel($$$); showGraph.m gca _BATCHに読み飛ばせる部分がある xlabel(***); ylabel($$$); 12年11月26日月曜日 21
  • 22. スクリプトと関数を切り分ける 登場順を意識する 名前に情報を詰め込む コメントを大事に使う ゴミを残さない 12年11月26日月曜日 22
  • 23. 登場順を意識する 先頭の情報は最も大事 混ぜるな危険!スクラッチブルに 終わったのか?done出力 更新は誰が?いつ?日付とauthor 12年11月26日月曜日 23
  • 24. 先頭の情報は最も大事 convertMat2Nsn_BATCH.m convertMat2Nsn_BATCH.m %function [w w_matrix] = % Convert Mat to Nsn file. convertMat2Nsn( % 1 : check Mat file existing data_matrix, num_cell, N_0) % 2 : check Mat format. % 3 : convert. if exist(‘abc.mat’) : スクリプト?関数? end 引数に必要なもの? 続きの内容を容易に追える clearが無かったら? 12年11月26日月曜日 24
  • 25. 混ぜるな危険!スクラッチブルに num=5 for kk=1:20 kkMax=20 data=load([‘svsv/fmri/data/’ kk]); resA{kk}=calcA(data); for kk=1:kkMax end data=load([‘sv/fmri/data/’ kk]); resA{kk}=calcA(data); num = 5; end calcB(resA,num); calcB(resA,num); 処理とパラメータが混在 処理とパラメータが別 12年11月26日月曜日 25
  • 26. 終わったのか? done出力 num=5 num=5 kkMax=20 kkMax=20 for kk=1:kkMax for kk=1:kkMax data=load([‘sv/fmri/data/’ kk]); data=load([‘sv/fmri/data/’ kk]); resA{kk}=calcA(data); resA{kk}=calcA(data); end end calcB(resA,num); calcB(resA,num); fprintf(‘%s Donen’, mfilename); 終わったのか不明 Doneと出力されたら終了 mfilenameも有効 12年11月26日月曜日 26
  • 27. 更新は誰が?いつ?日付とauthor % Do abc % Do abc % 1 : check inputs. % 1 : check inputs. % 2 : execute abc. % 2 : execute abc. % Modified By: K*** Harada kharada at ****.co.jp 12/09/26 if ~checkArgs(abc) error(‘’); if ~checkArgs(abc) end error(‘’); exec(abc); end exec(abc); いざという時誰に聞けば? 最も良く知る人が把握可能 12年11月26日月曜日 27
  • 28. スクリプトと関数を切り分ける 登場順を意識する 名前に情報を詰め込む コメントを大事に使う ゴミを残さない 12年11月26日月曜日 28
  • 29. 名前に情報を詰め込む 名前だけでバグを防ぐ スコープの意識 難しく考えないで命名規則 tempは誰も喜ばない 12年11月26日月曜日 29
  • 30. 名前だけでバグを防ぐ for row = 1:10 for ii = 1:10 for col = row:20 for jj = ii:20 if matrix{row, col} ~=NaN if matrix{ii,jj} ~=NaN oneData = 6*data{row, col}; calcB(6*data{ii,jj}, label{ii,ii}); oneLabel = label{row, row}; end calcB(oneData,oneLabel); end end end end 意味のある変数名は end バグに気付きやすい 意味のない変数名は 単数名or複数名の使い分けも良い バグに気付きにくい 12年11月26日月曜日 30
  • 31. スコープの意識 for rowCounter = 1:10 for rowCounter = 1:10 for colCounter = rowCounter:20 for colCounter = rowCounter:20 if ~exist(temp) if ~exist(temp) temp = data{rowC,colC}; temp = data{rowC,colC}; end end end end end end 別の処理部分に影響させない clear temp; 別の処理部分に影響する可能性 for temp=1:20 for temp=1:20 showNanika; showNanika; end end 12年11月26日月曜日 31
  • 32. 難しく考えないで命名規則 similaritymatrix SIMILARITYMATRIX similarityMatrix : 変数 SimilarityMatrix SIMILARITY_MATRIX : 定数 similarity_matrix SimilarityMatrix : クラス sm これ以外であっても、 ソース内で統一されていれば可 変数名の長さ∝変数のスコープ 12年11月26日月曜日 32
  • 33. tempは誰も喜ばない calcB(calcA()); or temp = calcA(); calcB(temp); resultCalcA = calcA(); 何が入っているのか? calcB(resultCalcA); 再利用されるのか? clear resultCalcA; 要追跡 追跡不要 12年11月26日月曜日 33
  • 34. スクリプトと関数を切り分ける 登場順を意識する 名前に情報を詰め込む コメントを大事に使う ゴミを残さない 12年11月26日月曜日 34
  • 35. コメントを大事に使う 鉄は熱いうちに、コメントは覚えているうちに 重要なことを足す 疑問、質問、こうなったらバグだ!も書く パラメータだけコメント化が許される %%は部分処理と現在地確認に用いる 12年11月26日月曜日 35
  • 36. 鉄は熱いうちに、コメントは覚えているうちに % Parameters % Parameters A = [1 2 3]; A = [1 2 3]; % do X % do X resultX = execX(A); resultX = execX(A); % Test from resultX = execY(A); resultX = execY(A); % Test to % do B インラインでもOK execB(resultX); % do B 食事後すぐ元通りにできるか? execB(resultX); 12年11月26日月曜日 36
  • 37. 重要なことを足す % Parameters % Define Parameter A A = [1 2 3]; A = [1 2 3]; % do X resultX = execX(A); resultX = execX(A); % execB % do B execB(resultX); execB(resultX); 見て分かることを書いてしまう コメントだけで 必要なことが抜けている コードが読める 12年11月26日月曜日 37
  • 38. 疑問、質問、こうなったらバグだ!も書く % Parameters % Parameters A = [1 2 3]; A = [1 2 3]; % do X % do X resultX = execX(A); resultX = execX(A); % execX失敗時は? % A未定義時はエラー発生 % do B execB(resultX); % do B execX失敗時は? execB(resultX); 気付きを記載 12年11月26日月曜日 38
  • 39. パラメータだけコメント化が許される % Parameters % Parameters A = [1 2 3]; A = [1 2 3]; A = {[1 2 3]; [2]; [3]}; % A = {[1 2 3]; [2]; [3]}; %multiple case % do X resultX = execX(A); % do X %resultX = execY(A); % Cell resultX = execX(A); 死んでいるパラメータ 設定可能なパラメータを示す 処理内容にコメント 処理内容はパラメータにだけ依存させる 12年11月26日月曜日 39
  • 40. %% は部分処理と現在地確認に用いる % Parameters %% Parameters A = [1 2 3]; A = [1 2 3]; % A = {[1 2 3]; [2]; [3]}; % A = {[1 2 3]; [2]; [3]}; % do X %% do X resultX = execX(A); resultX = execX(A); パラメータの設定確認など パラメータの設定確認他 部分処理ができない 部分処理が可能 今どの部分の処理を実行中? 「現在地」を把握可能 12年11月26日月曜日 40
  • 41. スクリプトと関数を切り分ける 登場順を意識する 名前に情報を詰め込む コメントを大事に使う ゴミを残さない 12年11月26日月曜日 41
  • 42. ゴミを残さない 変数一覧には重要性の表記がない 一時的変数は即消し スクリプトが出力の責任を持つ 未使用コードはVCSで積極的に消す 12年11月26日月曜日 42
  • 43. 変数一覧には重要性の表記がない 実行後のWorkspace ii double 8 実行後のWorkspace jj double 55 matrix cell matrix cell resultX double 1 a logical true 必要な結果のみを残す 必要な結果は何? saveで全変数の保存も有効 12年11月26日月曜日 43
  • 44. 一時的変数は即消し [temp data] = calcA(); [temp data] = calcA(); calcB(data); calcB(data); clear temp; tempは残る tempは残らない 12年11月26日月曜日 44
  • 45. スクリプトが出力の責任を持つ %% Parameters close all; A = [1 2 3]; clear; execX(A) %% Parameters A = [1 2 3]; [temp data] = calcA(); : ww = fopen(‘test.txt’); calcB(data); close all; fclose(ww); clear; calcBでエラー&中止時は? 初期化操作close all;clear;で 出力に責任を持つ 12年11月26日月曜日 45
  • 46. 未使用コードはVCSで積極的に消す % Parameters A = [1 2 3]; % Parameters % A = {[1 2 3]; [2]; [3]}; A = [1 2 3]; % A = {[1 2 3]; [2]; [3]}; % do X resultX = execX(A); % do X %resultX = execY(A); resultX = execX(A); %resultX = execZ(A); コメントインすると 必要な処理のみ残す すぐ使えてしまう VCSを使えばすぐ確認可能 12年11月26日月曜日 46
  • 47. まとめ スクリプトと関数を切り分ける 登場順を意識する 名前に情報を詰め込む コメントを大事に使う ゴミを残さない 12年11月26日月曜日 47