2016-07-18 4 views
0

Matlab : 함수의 호출자가 다른 곳에있는 동안 해당 함수를 읽는 함수에 상대적으로 위치한 데이터 파일을 읽으려면 어떻게해야합니까? 그래서 나는 다음과 같은 별자리가 :Matlab : 함수 위치를 기준으로 파일을 읽는 방법?

X:\callScript.m 
Y:\myFunction.m 
Y:\data\dataFile.txt 

callScript.m

addpath('Y:\'); 
myFunction(); 

이 myFunction.m

function myFunction() 
    fid = fopen('./data/dataFile.txt'); % < does not work! 
    % ... read something ... 
    fclose(fid); 
end 

답변

1

내가 더 좋은 방법이 할 생각을하지만,이도를 트릭을하십시오

function myFunc() 
    path_myFunc = which('myFunc'); % get myFunc's full path 
    path_myFunc = path_myFunc(1:find(path_myFunc,10,'last'); % Find last '\'(=10) 
    fid = fopen([path_myFunc,'\data\datafile.txt']); 
    % ... read something ... 
    fclose(fid); 
end 
+1

경로 경로를 얻으려면'path_myFunc = fileparts (which ('myFunction'))'([fileparts] (http://mathworks.com/help/matlab/ref/fileparts.html))를 사용하는 것이 좋습니다. 함수. 그 다음에'strcat' 대신'fullfile (path_myFunc, 'data', 'datafile.txt')'([fullfile] (http://mathworks.com/help/matlab/ref/fullfile.html))을 사용하십시오. 전체 경로. – serial

+0

감사합니다. 좋은 생각 인 것 같습니다. 불행히도,'which는'myFunct' (''myFunc 'no found')에 대한 빈 경로를 반환합니다. – matheburg

+0

당신이 함수 "myFunction"을 명명했기 때문에'which ('myFunction ')' – serial

관련 문제