3
2

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 3 years have passed since last update.

【MATLAB】エディタ上での実行時にmファイルのフォルダを自動的に現在のフォルダに設定(Windows)

Last updated at Posted at 2021-04-05

はじめに

MATLABは現在のフォルダが基準であるため、現在のフォルダを無意識のうちに変えて、mファイルが本来とは異なる場所でmファイルを実行してしまうと、特にファイルの入出力関係で問題になることが(私だけかもしれないが)多々あります。
(読み込みデータがあればエラーがでるだけだが、出力する場合はフォルダがごちゃごちゃになり、後々の整理が大変なことになることも。。。)

対策

それを防ぐために、Windowsであればmファイルの先頭に以下のようなコード

if ispc % Windowsであれば実行
    tmp= matlab.desktop.editor.getActive;       % 現在表示しているファイルのパス
    [filepath,~,~] = fileparts(tmp.Filename);   % 現在表示しているファイルのフォルダ名の取得
    cd(filepath);                               % 現在表示しているファイルのフォルダを現在のフォルダに設定
end

を追加すれば、エディタ上の実行の度に、実行したmファイルがあるフォルダを現在のフォルダに設定することができます。
なお、UNIX系ではエラーになるので if ispc でwindowsかどうか判定しています。

UNIX系の対処法も(多分ですが)あるのではないかと思います。

ご意見等ありましたら、よろしくお願いします。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?