writing a function in matlab

2 次查看(过去 30 天)
Hi!
I wrote this file to evalute some .TXT file.
I want to write it as a function. I dont know what to write as Input and Output
%
clear all
close all
clc
format long
for i=1:30
data=[];
fileID = fopen(['measurement_' num2str(i) '.txt']);
block = textscan(fileID, '%s','Delimiter','\n');
data=[data; block];
fclose(fileID);
compact_data=vertcat(data{:});
compact_data(1:29:end)=[];
compact_data(1:28:end)=[];
result_file=fopen(['result_probe_' num2str(i) '.txt'],'w');
fprintf(result_file,'%s\r\n',compact_data{1:1:end});
clear all
end
I wish you could help to transform this in a function whre i could give the input files ond get the result_probe files
Thank you

采纳的回答

John Petersen
John Petersen 2013-1-24
You can write your function like this:
function [out] = myfunction(filenums)
%
%
n = 0;
out = zeros(length(filenums),3);
for i=filenums
data=[];
fileID = fopen(['measurement_' num2str(i) '.txt']);
try
block = textscan(fileID, '%s','Delimiter','\n');
data=[data; block];
fclose(fileID);
compact_data=vertcat(data{:});
compact_data(1:29:end)=[];
compact_data(1:28:end)=[];
catch
end
try
result_file=fopen(['result_probe_' num2str(i) '.txt'],'w');
fprintf(result_file,'%s\r\n',compact_data{1:1:end});
fclose(result_file);
catch
n = n +1;
out(n,:) = [i, fileID, result_file];
end
end
end
Usage would be:
out = myfunction(1:30);
The inputs give you the option to select specific files, the output gives you an array that tells you which files were successfully opened. Any -1 in a column signifies that the corresponding file failed to open.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Dialog Boxes 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by