Function

I'd like to be able to apply this function loads,plots and saves figure data from a text file, to every file in a directory, such that when I type FunctionName(some directory), the function forks...
this is my code:
function plot;
files = dir('*.txt');
for i=1:length(files)
data = load(files(i).name);
filename=[files(i).name];
plot(data);
saveas(h,filename,'fig');
close;
end
end

 采纳的回答

Fangjun Jiang
Fangjun Jiang 2011-11-9

0 个投票

  1. plot() is a built-in function so you should not name your own function as plot.
  2. It is better to have an input argument specify the folder so you can use it to apply to many folders.
  3. When load or save, it's always better to specify the full path of the file.
  4. When you try to get the file name, you need to get rid of the .txt extension.
  5. close() needs to specify the figure handle.
function MyPlot(PathStr)
files = dir(fullfile(PathStr,'*.txt'));
for i=1:length(files)
data = load(fullfile(PathStr,files(i).name));
filename=strrep(files(i).name,'.txt','');
f=figure;
plot(f,data);
saveas(h,fullfile(PathStr,[filename,'.fig']));
close(f);
end

4 个评论

Baba
Baba 2011-11-9
Do I need to define what PathStr is anywhere else? Or should I be able to just type in MyPlot(some path) to perform this function on all files in that folder?
Yes, for example, MyPlot('C:\MyDocument\Data')
Baba
Baba 2011-11-9
Getting an error:
??? Undefined function or variable 'textfiles'
textfiles being the subfolder name where textfiles are located
I use myPlot(textfiles)to call the function
myPlot('textfiles')

请先登录,再进行评论。

更多回答(1 个)

Daniel Shub
Daniel Shub 2011-11-9

0 个投票

What problems are you having. the code looks pretty close. You don't define h, so I just replaced it with gcf (the current figure). Your function didn't take in the directory name like you need (or make use of the directory name).
function FunctionName(DirectoryName)
cd(DirectoryName)
files = dir('*.txt');
for i=1:length(files)
data = load(files(i).name);
filename=[files(i).name];
plot(data);
saveas(gcf,filename,'fig');
close;
end
end

1 个评论

Baba
Baba 2011-11-9
the problem is when I type in FunctionName(DirectoryName)
i get an error:
??? Undefined function or variable 'DirectoryName'.
For DirectoryName I typed in a folder within the working directory which contains my text files

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 Environment and Settings 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by