MATLAB Answers

Create multiple files via for loop

17 views (last 30 days)
Ivan Mich
Ivan Mich on 1 Mar 2021
Answered: Ivan Mich on 2 Mar 2021
I have a question about a code. I use this script in order to read file and making calculations. Finally i export my data to an output (txt file). The point is That i would like to create multiple file by reading multiple files and creates multiple outputs.
clc
clear
filename='data1125.xlsx'
[d1,tex]= xlsread(filename);
A1=d1(:,1);
B1=d1(:,2);
C1=d1(:,3)
results=mean(C1)
A=[{filename(1:4)} num2str(results)]
writecell(A,[char(filename(1:4)), '.txt'],'Delimiter','tab')
I think I should use for loop such as:
filename= dir('*.xlsx')
for k = 1:numel(filename)
end
Could you please help me?

Accepted Answer

Ivan Mich
Ivan Mich on 2 Mar 2021
The code that works is
clc
clear
%mean IMM
filename= dir('*km.xlsx')
for k = 1:numel(filename)
thisfile = filename(k).name ;
t = xlsread(thisfile)
A1=t(:,1);
B1=t(:,2);
C1=t(:,3)
results=mean(C1)
A=[{thisfile(1:4)} num2str(RESULTS)]
writecell(A,[char(thisfile(1:4)),'mean',thisfile(8:12) '.txt'],'Delimiter','tab')
end

More Answers (1)

Allen
Allen on 1 Mar 2021
You can use uigetfile to easily select mutliple files and make the filename acquisition process a little more simple.
% Prompts user to select *.xlsx file(s), with the starting location as the active MATLAB folder.
% Returns the file path and filename(s).
msg = "Select all *.xlsx data file(s) for processing"
[path,files] = uigetfile(fullfile(pwd,'*.xlsx'),msg,"MultiSelect","on");
Added your normal code to a loop. This task can be simplified, but using this format to make interpretation easier. Also, it is recommended to use readmatrix instead of xlsread, as it is much quicker.
% If path is numeric, no files where selected with uigetfile function
if ~isnumeric(path)
file = cellstr(file); % Ensures that the varible is a cell array
% previous conversion needed to prevent errors if only a single file was selected
for i=1:length(filename)
filename = fullfile(path,file{i}); % Combines the path and filename
% Original code
[d1,tex] = xlsread(filename);
A1 = d1(:,1);
B1 = d1(:,2);
C1 = d1(:,3)
results = mean(C1)
A = [{filename(1:4)} num2str(results)]
writecell(A,[char(filename(1:4)), '.txt'],'Delimiter','tab')
end
end

Community Treasure Hunt

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

Start Hunting!