How to create a loop for this excel data
Show older comments
So i currently have this code
clear all,close all
%InputData%
inputdata=xlsread('01.csv');%extract all data from first jump%
idx = find(inputdata(:,5) == 0);
zeroMatrix = inputdata(idx,5);
oneMatrix=zeroMatrix+1
t=sum(oneMatrix)*0.001
%Variables%
g=-9.81
%Calculations%
MH1=0.5*-g*(t^2)
This code basically takes data from a excel spreasheet (number 1) and works out MH1, I want to create a loop so that matlab takes spreadsheet 2 and creates MH2, with spread sheet 3 creating MH3 and so on and so on, I have over 50 spreadsheets to work with.
Thankyou :)
3 Comments
Image Analyst
on 31 Dec 2018
I don't see any Excel workbook.
Also you forgot to attach the CSV text file '01.csv'. Please attach this text file so we can run your code.
And also attach the Excel workbook(s) that "spreadsheet 2" and "spreadsheet 3" are in.
Image Analyst
on 31 Dec 2018
Are you simply confused about how to use the code in the FAQ to transfer text from CSV text files to Excel workbooks using the csvread() and xlswrite() functions in the middle of the loop over all text files?
Louis Cook
on 31 Dec 2018
Edited: Louis Cook
on 31 Dec 2018
Answers (1)
Cris LaPierre
on 31 Dec 2018
Edited: Cris LaPierre
on 31 Dec 2018
You need to capture all the fieldnames at once. Then have the rest of your code execute inside a for loop, once for each file.
fileNames = {'Name1.csv','Name2.csv'}
for f = 1:length(fileNames)
inputdata=xlsread(fileNames{f});%extract all data from first jump%
idx = find(inputdata(:,5) == 0);
zeroMatrix = inputdata(idx,5);
oneMatrix=zeroMatrix+1
t=sum(oneMatrix)*0.001
%Variables%
g=-9.81
%Calculations%
MH(f).data=0.5*-g*(t^2)
end
Note I changed how the data gets stored from a matrix to a structure. Now you'd access the data using MH(1).data, MH(2).data, etc.
2 Comments
Louis Cook
on 4 Jan 2019
Edited: Cris LaPierre
on 4 Jan 2019
Cris LaPierre
on 4 Jan 2019
If you prefer to have them hardcoded, I'd do something like this (in 18b)
num = 10:105;
ext = ".csv";
JumpData = "0" + [1:9] + ext;
JumpData = [JumpData, num+ext];
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!