MATLAB: Function

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

Best Answer

  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