How to extract multiple excel tabs into MATLAB
이전 댓글 표시
Hello All,
I have the following code: [num,text] = xlsread('C:\Users\mahnoor.saeed\Documents\P18 Full SRDC MIDAS Simulations');
The excel sheet consists of 40 tabs (each has over 3,000 columns and 20 rows but this is the same in each sheet) but this piece of code only reads the data from the first page of the sheet.
How can I write a loop function to import the data from all 40 tabs as MATLAB variables as I later need to plot certain data.
Any help would be appreciated.
Thankyou.
답변 (1개)
Stephen23
2023년 6월 22일
Do not use deprecated XLSREAD.
It is very odd that your filename does not have a file extension, I fixed that for you:
F = 'C:\Users\mahnoor.saeed\Documents\P18 Full SRDC MIDAS Simulations.xlsx';
S = sheetnames(F);
D = cell(size(S));
for k = 1:numel(S)
D{k} = readtable(F, 'Sheet',S(k));
end
댓글 수: 39
Mahnoor
2023년 6월 22일
Stephen23
2023년 6월 22일
"how can I split 'D' into 40 seperate tables (representing each tab)..."
Do you incorrectly think that D only consists of one table? It doesn't: D already consists of 40 separate tables, all conveniently stored in one cell array which you can trivially and efficiently access using basic MATLAB indexing:
If you imagine that creating lots of separate variables would be good data design, then you need to understand that dynamically creating 40 variables in the workspace forces you into writing slow, complex, inefficient, obfuscated, buggy code that is hard to debug every time you try to access those tables in a loop:
So your concept is slow, inefficient, makes processing your data harder. In contrast, the single simple cell array that I showed you makes accessing your data easier. Which is why I used it in my answer. You should too.
Stephen23
2023년 6월 23일
"I believe one piece of code can be written for this and repeated 40 times for each table. Would you please be able to advise on how to start with this and what the correct format would be?"
Why not just use the loop that is already in my answer? It already loops over all of the sheets.
If you really want a second loop, then do this:
for k = 1:numel(D)
T = D{k};
.. your code, do whatever you want with table T
end
Mahnoor
2023년 6월 25일
Stephen23
2023년 6월 25일
"Where is the plotting function in this?"
Where I wrote "your code" is where you put your code.
Mahnoor
2023년 6월 25일
How can we do that? You didn't attach your workbook(s) or explain what "need to plot certain data" means. What certain data? All we can recommend is plot
help plot
Mahnoor
2023년 6월 25일
Image Analyst
2023년 6월 25일
I'll try. Like I said, attach your workbook.
@Mahnoor: we cannot import and plot a screenshot of data. Please upload a sample data file by clicking the paperclip button. It does not have to be your complete data file: it only needs to contain two or three worksheets and perhaps one hundred rows per worksheet (experiment until you get a reasonable filesize that can be uploaded here). Do not change the format or arrangement of the data on the worksheets.
"I would like to plot nEmotor + nEngine (both on y-axis) against Time (x-axis) for each table, so bascially 40 times"
Does that mean you expect 40 plots each with 2 lines on it, or 1 plot with 80 lines on it?
Mahnoor
2023년 6월 26일
F = 'P18 Full SRDC MIDAS Simulations.xlsx';
S = sheetnames(F);
for k = 1:numel(S)
T = readtable(F, 'Sheet',S(k));
plot(T.Time,T.nEMotorR,'r-*', T.Time,T.nEngine,'b-+')
title(S(k),'Interpreter','none')
legend("nEMotorR","nEngine")
xlabel("Time (unit?)")
ylabel("???? (unit?)")
saveas(gcf,sprintf('%s.png',S(k)))
end
I added markers to the plot just to demonstrate that the two lines overlap. Of course you can change the color, markers, etc to suit your own needs. The above graphic shows only the last plot, you can find all plots saved in PNG files:
dir *.png
Mahnoor
2023년 6월 27일
"And split it into column vectors so the sheet is split into many variables in the workspace."
Best avoided: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval
Much better: access the data in the table (rather than slow, complex, inefficient, buggy code that magically creates lots of new variables in the workspace).
"Using code, I would like to create a new variable for 'MSideShaftSUM' which adds all of the values of 'MSideShaftRL' to the values of 'MSideShaftRR'."
T = readtable('SRDC Script Test Try.xlsx', 'Sheet','Autobahn');
T.MSideShaftSUM = T.MSideShaftRL + T.MSideShaftRR % did you try adding them?
"And another new variable for 'nWheel Delta' which subtracts all of the values in 'nWheelRL' from the values of 'nWheelRR'."
I showed you addition, I am sure that you can handle the subtraction yourself.
Mahnoor
2023년 6월 29일
"thankyou so so much for your support and for answering all of my questions. It has been very very helpful. Thankyou once again."
Then please remember to click the Accept button. You can also vote for answers that help you.
"is there any quick way of repeating the file path for the below pieces of code rather than copy/pasting the new path each time into a new line of code"
Of course, just use FULLFILE, e.g.:
P = 'C:\Users\mahnoor.saeed\Documents\P17R Test Cycles';
T = readtable(fullfile(P,'Read Track.xlsx'), 'Sheet','VHS Track');
You can use P as many times as you want.
Mahnoor
2023년 7월 4일
Stephen23
2023년 7월 4일
" I would like to enhance the resoultion of the image and still save it at the same time."
Try increasing the resolution.
"Is it possible in any way to view 3/4 plots at one time (like the picture below) rather than opening them individually and placing them like this?"
or
Mahnoor
2023년 7월 29일
"How many seconds (duration) is the the torque in the following conditions: 0 to 100 Nm, 101 to 200 Nm, 201 to 300 Nm, etc. all the way up to the final limit of 1,000 Nm. And would also need it in the opposite direction from 0 to - 100 Nm, - 101 to -200 Nm. Bascially, in easier terms, trying to find out how long did each torque happen for (time at each torque). "
This might get you started:
T = readtable('Autobahn Comfort Matlab.xlsx');
T.MPowerTrain = T.MEngine + T.MEMotorR
V = -200:100:1000
histogram(T.MPowerTrain,V) % lets have a quick look first:
C = histcounts(T.MPowerTrain,V) * 0.01 % 0.01 = sample step
This means:
- between -200 and -100 there were 0 seconds
- between -100 and 0 there were 28.69 seconds
- etc.
Alternatively you could probably leverage some of the features of the TIMETABLE class.
Stephen23
2023년 7월 29일
Q1: "But for some reason, the variables T, V and C wont appear in the command window. How can I make the variables appear in the command window?"
You can display variables in the command window by calling DISP or FPRINTF... or by simply removing the semi-colon at the end of the lines where those variables are defined.
Q2: "In the histogram plot, what is the y-axis representing?"
By the definition of histogram, this is a count of how many elements occur within those bins. It is not normalized.
Q3a: "What is the histcounts function exactly doing?"
By the defnition of histogram, it counts how any elements occur within those bins. It is not normalized.
Q3b: " Is there any way to more easily read the plotted data maybe as a table later on as it is a bit difficult to interpret especially since the variables do not appear in my command window?"
I have no idea what you think is "more easily read", that sounds like something very subjective that would depend a lot on your needs, experience, etc. Of course you can put those values into a table, if you wish.
There is nothing stopping you from displaying them in the command window either.
Mahnoor
2023년 7월 29일
Stephen23
2023년 7월 29일
"Would it be possible to view the data in the way below possibly in the command window?"
Yes, look at ARRAY2TABLE, TABLE, etc.
Mahnoor
2023년 7월 30일
Stephen23
2023년 7월 30일
"Would you know how to fix the code required to run the table and view it in the command window and workspace?"
Look at the example: it defines the variables AGE, WEIGHT, and HEIGHT before calling TABLE.
Now look at your code: do you define INTERVALOFTORQUE and DURATIONOFTORQUE before calling TABLE? (hint: no)
Mahnoor
2023년 7월 30일
"Not sure how to make [1 x13 double] and [1 x 12 double] appear exactly as all of the values of V and C like how it is in the window? And how to put all of these values of V and C under their associated columns?"
You need to make those variables column vectors of the same length, e.g.:
IntervalOfTorque = V(:);
DurationOfTorque = [C(:);NaN];
Mahnoor
2023년 7월 31일
Dyuman Joshi
2023년 7월 31일
This is very simple stuff @Mahnoor, you should be figuring this out on your own. Atleast you should be trying to figure out things on your own.
Read the error, try to understand what it says. Look at the code, see what it does.
C(:)
The above command returns the content in C as a column vector.
To add another element at the end of column vector (i.e. performing vertical concatenation), you need to use a semi-colon instead of a comma.
Just use
[C(:);NaN]
Stephen23
2023년 7월 31일
@Dyuman Joshi: thank you for the explanation. I fixed my comment.
Mahnoor
2023년 7월 31일
"Would higly appreciate any help with this."
You did not upload the corresponding data file with your last comment, but the last file you uploaded does not have any variables named MSIDESHAFTRL or MSIDESHAFTRR. If the file does not contain those headers then they will not exist in the imported data table:

"I have tried to rename the variables and change names"
You seem to be using the shotgun approach to debugging. That is not very efficient.
Mahnoor
2023년 7월 31일
"I am trying to use 2 inputs against time which is engine and motor speed but cannot seem to get the below code for the histogram to work."
What makes you think that it is possible to supply two inputs to HISTOGRAM like that?
I don't see anything in the HISTOGRAM documentation that supports that syntax.
Mahnoor
2023년 8월 1일
Mahnoor
2023년 8월 9일
카테고리
도움말 센터 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!






















