writing a function in matlab

2 visualizzazioni (ultimi 30 giorni)
Rica
Rica il 23 Gen 2013
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

Risposta accettata

John Petersen
John Petersen il 24 Gen 2013
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.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by