필터 지우기
필터 지우기

function

조회 수: 2 (최근 30일)
Baba
Baba 2011년 11월 15일
My code pulls some data out of binary files and puts this data into an Array. When the code is done running I can see this Array in the Workspace window. However, When I turn my code into a function, once executed, I can not see the resulting Array int the Workspace.
function getchan(wd)
files = dir('*.bin');
DATA=[];
tic;
for i=1:100 %length(files)
[d] = readbin (files(i).name);
data=(d(:,1));
DATA=[DATA;data]
end
toc;
end
I also would like to be able to call this function and provide the directory to execute on as in getchan('directory') however, with code as is now, I have to make that directory the current directory first and then run the function by typing getchan

채택된 답변

Sven
Sven 2011년 11월 15일
Baba, variables created inside a function are limited to that function's scope. If you want to have DATA available outside the function, you should make that function return the DATA variable:
function DATA = getchan(wd)
% Search for .bin files in the wd directory
files = dir(fullfile(wd,'*.bin'));
DATA=[];
% Loop over every .bin file and build up DATA
for i=1:length(files)
% Make sure we're reading from the wd directory
d = readbin (fullfile(wd,files(i).name));
% Append the first column of what we read to DATA
DATA=[DATA; d(:,1)];
end
end
Now you can simply call:
MY_DATA = getchan(pwd)
Note above that I've also used "fullfile", passing in "wd" from your function to make your function work specifically on the directory stored in "wd".
  댓글 수: 10
Sven
Sven 2011년 11월 16일
Baba, try:
doc dir
It says:
"... Results appear in the order returned by the operating system."
Sven
Sven 2011년 11월 16일
Don't worry, you're allowed to be new to programming. You'll get good help here especially if you ask clear, concise questions including the code you're using.
I've noticed one or two of your questions that are answered by the MATLAB documentation - that might be a useful source. For example, if your next question is, say, about how to order the results from the dir() command, then searching the docs for "sort" will almost certainly answer your question.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by