You are now following this question
- You will see updates in your followed content feed.
- You may receive emails, depending on your communication preferences.
How to extract multiple excel tabs into MATLAB
15 views (last 30 days)
Show older comments
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.
Answers (1)
Stephen23
on 22 Jun 2023
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 Comments
Mahnoor
on 22 Jun 2023
Thankyou very much @Stephen23 for your answer. It seems to be working but how can I split 'D' into 40 seperate tables (representing each tab) where each table/tab will will be comprised of several numbers. Please refer to the attached image.
Stephen23
on 22 Jun 2023
"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.
Mahnoor
on 23 Jun 2023
Edited: Mahnoor
on 23 Jun 2023
I understand that D is split into 40 seperate tables. Each table has the same first row (Time, Distance etc..) but the numbers in each are just different. I would like to plot nEmotor + nEngine (both on y-axis) against Time (x-axis) for each table, so bascially 40 times. 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? Please refer to the attached image.
Thankyou so much
Stephen23
on 23 Jun 2023
"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
on 25 Jun 2023
Thankyou for your response. Where is the plotting function in this? I would like to plot nEmotor + nEngine (both on y-axis) against Time (x-axis) for each table, so bascially 40 times. Im not sure how to write a loop for plotting and repeating for 40 of the tables?
Stephen23
on 25 Jun 2023
"Where is the plotting function in this?"
Where I wrote "your code" is where you put your code.
Mahnoor
on 25 Jun 2023
Yes, would you be able to assist with the code please for how to plot? As Im not sure what it will be
Image Analyst
on 25 Jun 2023
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
PLOT Linear plot.
PLOT(X,Y) plots vector Y versus vector X. If X or Y is a matrix,
then the vector is plotted versus the rows or columns of the matrix,
whichever line up. If X is a scalar and Y is a vector, disconnected
line objects are created and plotted as discrete points vertically at
X.
PLOT(Y) plots the columns of Y versus their index.
If Y is complex, PLOT(Y) is equivalent to PLOT(real(Y),imag(Y)).
In all other uses of PLOT, the imaginary part is ignored.
Various line types, plot symbols and colors may be obtained with
PLOT(X,Y,S) where S is a character string made from one element
from any or all the following 3 columns:
b blue . point - solid
g green o circle : dotted
r red x x-mark -. dashdot
c cyan + plus -- dashed
m magenta * star (none) no line
y yellow s square
k black d diamond
w white v triangle (down)
^ triangle (up)
< triangle (left)
> triangle (right)
p pentagram
h hexagram
For example, PLOT(X,Y,'c+:') plots a cyan dotted line with a plus
at each data point; PLOT(X,Y,'bd') plots blue diamond at each data
point but does not draw any line.
PLOT(TBL,XVAR,YVAR) plots the variables xvar and yvar from the table
tbl. To plot one data set, specify one variable for xvar and one
variable for yvar. To plot multiple data sets, specify multiple
variables for xvar, yvar, or both. If both arguments specify multiple
variables, they must specify the same number of variables
PLOT(TBL,YVAR) plots the specified variable from the table against the
row indices in the table. If the table is a timetable, the specified
variable is plotted against the row times from the timetable.
PLOT(X1,Y1,S1,X2,Y2,S2,X3,Y3,S3,...) combines the plots defined by
the (X,Y,S) triples, where the X's and Y's are vectors or matrices
and the S's are strings.
For example, PLOT(X,Y,'y-',X,Y,'go') plots the data twice, with a
solid yellow line interpolating green circles at the data points.
The PLOT command, if no color is specified, makes automatic use of
the colors specified by the axes ColorOrder property. By default,
PLOT cycles through the colors in the ColorOrder property. For
monochrome systems, PLOT cycles over the axes LineStyleOrder property.
Note that RGB colors in the ColorOrder property may differ from
similarly-named colors in the (X,Y,S) triples. For example, the
second axes ColorOrder property is medium green with RGB [0 .5 0],
while PLOT(X,Y,'g') plots a green line with RGB [0 1 0].
If you do not specify a marker type, PLOT uses no marker.
If you do not specify a line style, PLOT uses a solid line.
PLOT(AX,...) plots into the axes with handle AX.
PLOT returns a column vector of handles to lineseries objects, one
handle per plotted line.
The X,Y pairs, or X,Y,S triples, can be followed by
parameter/value pairs to specify additional properties
of the lines. For example, PLOT(X,Y,'LineWidth',2,'Color',[.6 0 0])
will create a plot with a dark red line width of 2 points.
Example
x = -pi:pi/10:pi;
y = tan(sin(x)) - sin(tan(x));
plot(x,y,'--rs','LineWidth',2,...
'MarkerEdgeColor','k',...
'MarkerFaceColor','g',...
'MarkerSize',10)
See also TITLE, XLABEL, YLABEL, XLIM, YLIM, LEGEND, HOLD, GCA, YYAXIS,
PLOT3, SEMILOGX, SEMILOGY, LOGLOG, TILEDLAYOUT, HOLD, LEGEND, SCATTER
Documentation for plot
doc plot
Other uses of plot
alphaShape/plot
antenna/plot
Battery.Parameters/plot
Battery.Pulse/plot
Battery.PulseSequence/plot
BayesianOptimization/plot
blm/plot
cfit/plot
cgv.CGV/plot
clustergram/plot
clustering.evaluation.CalinskiHarabaszEvaluation/plot
comm.MemorylessNonlinearity/plot
conjugateblm/plot
cornerPoints/plot
customblm/plot
cylinderModel/plot
diffuseblm/plot
digraph/plot
driving.heremaps.LaneTopology/plot
driving.Path/plot
drivingScenario/plot
dspdata/plot
dtree/plot
empiricalblm/plot
fairnessMetrics/plot
frd/plot
graph/plot
HeatMap/plot
iddata/plot
idnlarx/plot
idnlhw/plot
imageviewset/plot
InflationCollisionChecker/plot
KAZEPoints/plot
lassoblm/plot
LayerGraph/plot
LeastSquaresResults/plot
lime/plot
LinearModel/plot
matlab.buildtool.Plan/plot
mixconjugateblm/plot
mixsemiconjugateblm/plot
mpc/plot
MSERRegions/plot
NLMEResults/plot
ntree/plot
opc.hda.Data/plot
opticalFlow/plot
parkingSpace/plot
pathPlannerRRT/plot
pcviewset/plot
phased.FMCWWaveform/plot
phased.LinearFMWaveform/plot
phased.MFSKWaveform/plot
phased.PhaseCodedWaveform/plot
phased.RectangularWaveform/plot
phased.SteppedFMWaveform/plot
phytree/plot
polyshape/plot
predmaint/plot
prob.NormalDistribution/plot
propagationData/plot
quantum.gate.CompositeGate/plot
RepeatedMeasuresModel/plot
rfchain.rfchain/plot
roadrunnerHDMap/plot
rocmetrics/plot
SE3/plot
semiconjugateblm/plot
sfit/plot
shapley/plot
SimBiology.fit.ParameterConfidenceInterval/plot
SimBiology.fit.PredictionConfidenceInterval/plot
SimBiology.gsa.ElementaryEffects/plot
SimBiology.gsa.MPGSA/plot
SimBiology.gsa.Sobol/plot
simscape.logging.Node/plot
simscape.logging.Series/plot
simscape.logging/plot
Simulink.sdi.DatasetRef/plot
Simulink.SimulationData.Dataset/plot
Simulink.SimulationData.Parameter/plot
slrealtime.ProfilerData/plot
tall/plot
timeseries/plot
umargin/plot
vehicleCostmap/plot
wavelet/plot
wdectree/plot
Mahnoor
on 25 Jun 2023
Hello @Image Analyst
I have use the following code provided by @Stephen23
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
When this code runs, I get this as a result:
(40 tables in one variable 'D')
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1419233/image.png)
Each table looks like this:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1419238/image.png)
I would like to plot nEmotor + nEngine (both on y-axis) against Time (x-axis) for each table, so when the code runs, the plots automtically pop up. Im not sure how to write a loop for the repition of plotting the data from 40 tables.
Would you please be able to assist with this as I am quite new to MATLAB. Any help would be highly appreciated.
Thankyou.
Mahnoor
on 25 Jun 2023
Edited: Mahnoor
on 25 Jun 2023
Hello @Image Analyst
I have attached the mat file below, please do let me know if you can view it. Please ignore the green comments, the running code is right towards the end.
I cannot seem to attach the workbook, as its too huge and for some reasons even when its zipped, its still to large to upload.
But this is how the first few tabs look like in Excel
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1419263/image.png)
Thankyou so much for trying.
Stephen23
on 26 Jun 2023
Edited: Stephen23
on 26 Jun 2023
@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
on 26 Jun 2023
Hello @Image Analyst, @Stephen23. I have uploaded the worksheet and have cut this down to 5 tabs with 100 rows each. I have not changed the format/arrangement of the data on the worksheets. I think it would be easier to visualize 40 plots, each with 2 lines on it. I hope this is sufficient information now. Thankyou both for your help.
Stephen23
on 26 Jun 2023
Moved: Stephen23
on 26 Jun 2023
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
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1419443/image.png)
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
230321_P17_Handling_Baseline.png 300323_P18_CD1B_EMode.png 300323_P18_SpecialSurfaces_Comf.png
300323_P18_CD1B_Comfort.png 300323_P18_H&G_Comfort_Pt.png
Mahnoor
on 27 Jun 2023
I do have another query (Im trying another Import technique from getting excel data into matlab), Im trying to upload the attached Excel sheet (with 1 tab) using the import button directly. And split it into column vectors so the sheet is split into many 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'. And another new variable for 'nWheel Delta' which subtracts all of the values in 'nWheelRL' from the values of 'nWheelRR'. I would like to do this direclty in MATLAB rather than doing it in Excel (The sheet is sent by another department where the sum and delta rows are not present).
I have attached my code and excel sheet below, and this will need to be manually imported using the 'Import' function on the Home page.
Would you please be able to assist with this? Once again, thankyou very much for your support @Stephen23
Stephen23
on 27 Jun 2023
"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?
T = 24001×19 table
Time Distance vCar rThrPedal MEngine MEMotorR MPowertrain MSideShaftRL MSideShaftRR NGear NGearEMotorR PEngine PEMotorR PPowertrain nEMotorR nEngine nWheelRL nWheelRR MSideShaftSUM
____ ________ _____ _________ _______ ________ ___________ ____________ ____________ _____ ____________ _______ ________ ___________ ________ _______ ________ ________ _____________
0 0.05 220 42.3 0 0 0 940.5 940.5 8 8 0 0 0 17948 7938.5 1622 1622 1881
0.01 0.66 220 42.2 61.2 109.91 171.11 1089.3 1084.8 8 8 48.1 92 140.1 7991.5 7494 1645.2 1645.4 2174.1
0.02 1.27 220.1 41.3 126.3 110.69 236.99 1192.4 1175.8 8 8 93.6 92 185.6 7935.1 7078.6 1638.3 1638.8 2368.2
0.03 1.88 220.2 40.1 192.4 111.91 304.31 1221.5 1203.1 8 8 134.8 92 226.8 7849.2 6693.5 1625.7 1626 2424.6
0.04 2.49 220.3 39.3 253.6 112.14 365.74 1206.6 1207.4 8 8 168.3 92 260.3 7833.1 6337.8 1626.2 1625.5 2414
0.05 3.1 220.4 38.6 280.5 111.65 392.15 1202 1220.7 8 8 176.4 92 268.4 7867.3 6003.6 1634.4 1633.5 2422.7
0.06 3.72 220.4 37.8 288.1 111.47 399.57 1218.4 1232.2 8 8 171.2 92 263.2 7879.8 5675.1 1636.7 1636.5 2450.6
0.07 4.33 220.5 36.9 295.6 108.71 404.31 1219.5 1235.5 8 8 165.6 90 255.6 7863.6 5350.1 1634 1633.8 2455
0.08 4.94 220.6 36 301.2 90.78 391.98 1155.7 1201.6 8 8 158.6 75 233.6 7842.8 5028.1 1632.6 1631.2 2357.3
0.09 5.55 220.7 35.2 305.9 72.27 378.17 1087.1 1168.7 8 8 150.8 59 209.8 7841 4708.4 1633.5 1631.5 2255.8
0.1 6.17 220.7 34.5 310.2 54.88 365.08 1032 1136.9 8 8 142.6 45 187.6 7847 4390.8 1634.8 1633 2168.9
0.11 6.78 220.8 33.8 314.2 39.21 353.41 984.1 1110.5 8 8 134.1 32 166.1 7848.9 4075.1 1635 1633.3 2094.6
0.12 7.39 220.9 33.1 317.9 24.51 342.41 934.1 1088.8 8 8 125.2 20 145.2 7847.1 3761.2 1634.6 1632.7 2022.9
0.13 8.01 220.9 32.5 321.2 10.73 331.93 546.9 730.3 8 8 117.4 9 126.4 7758.7 3490.8 1633.9 1631.9 1277.2
0.14 8.62 221 32 324.5 5.24 329.74 217.3 386.7 8 8 117.6 4 121.6 7689.6 3462.1 1620.3 1617.7 604
0.15 9.23 220.9 32 327.9 1.08 328.98 153.5 283.1 8 8 119.6 1 120.6 7734.7 3484.1 1622.9 1617.2 436.6
"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
on 29 Jun 2023
Hello @Stephen23, thankyou so so much for your support and for answering all of my questions. It has been very very helpful. Thankyou once again.
I do have one last question if thats okay, 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 (currently have 40 lines of individual code where each looks at the 'same' file location).
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1422588/image.png)
Stephen23
on 29 Jun 2023
Edited: Stephen23
on 29 Jun 2023
"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
on 4 Jul 2023
I have pressed the 'Vote' button but not sure where the 'Accept' one is? Thankyou very very much for your help. Apologies, I keep asking more questions.
Referring to the figure below, I would like to enhance the resoultion of the image and still save it at the same time. Would this code be sufficient or can it be made more efficient?
Code: exportgraphics (gcf, 'Plot 1 for Drivehsaft Torque.png', 'Resolution' ,300)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1426108/image.png)
Also, when the plots do appear in the current folder as images, I copy all of these at once (8 plots) and paste it in 1 folder under My Documents.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1426113/image.png)
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?
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1426118/image.png)
Thankyou so much once again
Stephen23
on 4 Jul 2023
" 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
on 29 Jul 2023
Thankyou for your help in regards to my initial question. Would you please be so kind and able to assist with the below?
I have generated this piece of code which displays a graph of Powertrain torque (Nm) vs Time (s) (similar to what was discussed before). This data has been taken from the attached excel file below and have added its pathway/location to the first line of the code so the data is read directly from the sheet. I have also attached the matlab code and excel sheet below for easy access.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1445012/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1445017/image.png)
I would like to do some kind of pivot table or a similar/another function to generate the information below once the graph has been run/ or during running.
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).
Ideally would like one column that displays the Time (s) and a second column that displays each duration of powertrain torque (Nm). Using the attached Excel sheet, around 103 cells in the Engine and Motor columns equates to a complete second.
Any help is highly appreciated. Thankyou.
Stephen23
on 29 Jul 2023
Edited: Stephen23
on 29 Jul 2023
"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
T = 24001×4 table
Time MEngine MEMotorR MPowerTrain
____ _______ ________ ___________
0 0 0 0
0.01 60.1 86.01 146.11
0.02 124.9 84.99 209.89
0.03 191.2 84.96 276.16
0.04 252.8 85.36 338.16
0.05 280.4 85.83 366.23
0.06 287.8 86.11 373.91
0.07 295.3 86.12 381.42
0.08 301.1 85.99 387.09
0.09 305.8 85.86 391.66
0.1 310.2 71.77 381.97
0.11 314.2 54.64 368.84
0.12 317.9 36.33 354.23
0.13 316.9 19.48 336.38
0.14 305.1 19.39 324.49
0.15 300.6 19.21 319.81
V = -200:100:1000
V = 1×13
-200 -100 0 100 200 300 400 500 600 700 800 900 1000
histogram(T.MPowerTrain,V) % lets have a quick look first:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1445112/image.png)
C = histcounts(T.MPowerTrain,V) * 0.01 % 0.01 = sample step
C = 1×12
0 28.6900 4.1400 2.3800 3.4100 28.4200 69.0200 47.3500 25.4800 6.6300 5.5100 18.9800
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.
Mahnoor
on 29 Jul 2023
Moved: Stephen23
on 29 Jul 2023
Thankyou for your help. Just a few questions:
Q.1 When I run this code, the variables for appear in the workspace as expected. 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?
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1445362/image.png)
Q.2 In the histogram plot, what is the y-axis representing?
Q.3 What is the histcounts function exactly doing?
Q.3 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?
Thankyou for your help.
Stephen23
on 29 Jul 2023
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
on 29 Jul 2023
Would it be possible to view the data in the way below possibly in the command window?
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1445377/image.jpeg)
Thankyou
Stephen23
on 29 Jul 2023
"Would it be possible to view the data in the way below possibly in the command window?"
Yes, look at ARRAY2TABLE, TABLE, etc.
Mahnoor
on 30 Jul 2023
I am using this code below as a reference to create a table. ![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1445727/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1445727/image.png)
I have done the follwing but doesnt seem to be working:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1445732/image.png)
Would you know how to fix the code required to run the table and view it in the command window and workspace?
Thankyou so much.
Stephen23
on 30 Jul 2023
"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
on 30 Jul 2023
Hello @Stephen23, I am trying to make my table like the above picture I had sent previously. 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?
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1445747/image.png)
Stephen23
on 31 Jul 2023
Edited: Stephen23
on 31 Jul 2023
"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];
Dyuman Joshi
on 31 Jul 2023
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]
Mahnoor
on 31 Jul 2023
Thankyou @Dyuman Joshi and @Stephen23. I do have another query, I am trying to replicate the code and run it on another plot. I have attched the initial image which shows that the table and histogram is produced for Powertrain torque.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1446322/image.png)
But, when I seem to do the same for the Driveshaft torque, in the second picture, the code gives the following error. I have tried to rename the variables and change names but still cant seem to get rid of the error.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1446327/image.png)
Would higly appreciate any help with this. Thankyou.
Stephen23
on 31 Jul 2023
Edited: Stephen23
on 31 Jul 2023
"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:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1446417/image.png)
"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
on 31 Jul 2023
Thankyou @Stephen23, that was my mistake was referring to the wrong Excel sheet and completely forgot to look at that specific line.
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. I have added a new variable to hold the addtional information on speed but still doesnt seem to be working. I have attached an updated Excel sheet which contain nEngine and nEMotorR.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1446592/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1446597/image.png)
Any hep would be highly appreciated. Thankyou.
Stephen23
on 1 Aug 2023
Edited: Stephen23
on 1 Aug 2023
"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
on 1 Aug 2023
Ah okay thanks @Stephen23, I was not aware that it was not possible. Will I have to take each input separetly (one for motor and for engine) and do an histogram accordingly and use the same technique:
C = histcounts(T.nEngine,V) * 0.01
C = histcounts(T.nEMotorR,V) * 0.01
Mahnoor
on 9 Aug 2023
It seems that I have got some error in my plots using the code below.
clear; close all; %do not comment
P = 'C:\Users\mahnoor.saeed\Documents\P17R Test Cycles'; %do not comment %change only this line
%% Use for plotting AutoBahn Comfort
T = readtable(fullfile(P,'Autobahn Comfort Matlab.xlsx'),'Sheet','Autobahn Comfort');
%% Plot #5 for Engine Torque (MEngine against Time)
figure ; plot (T.Time,T.MEngine, 'LineWidth',0.80)
xlabel('Time (s)'); ylabel('Engine Torque (Nm))')
ylim([-220 1200]); yticks(-220:142:1200)
legend('MEngine', 'Location', 'best')
title ('Engine Torque vs Time')
exportgraphics(gcf, 'Plot #5 for Engine Torque.png','Resolution',300)
%How many seconds is the engine torque in the following conditions?
T = readtable('Autobahn Comfort.xlsx');
T.MEngine;
V = -220:142:1200;
C = histcounts(T.MEngine,V) * 0.01;
Interval_Of_Torque_Nm = V(:);
Duration_Of_Torque_s = [C(:);NaN];
Engine_Torque = table(Interval_Of_Torque_Nm, Duration_Of_Torque_s, 'VariableNames',{'Interval of Engine Torque (Nm)','Duration of Engine Torque (s)'})
figure ; histogram(T.MEngine,V);
xlabel('Engine Torque (Nm)')
legend('Time (s)', 'Location', 'best')
title ('Duration of Engine Torque')
exportgraphics(gcf, 'Histogram #7 for Duration of Engine Torque.png','Resolution',300)
%
%% Plot #6 for Motor Torque (MEMotorR against Time)
figure ; plot (T.Time,T.MEMotorR, 'LineWidth',0.80)
xlabel('Time (s)'); ylabel('MEMotorR (Nm))')
yline(200, '--r', 'Motor torque limit of 200Nm'); yline(-200, '--r', 'Motor torque limit of -200Nm')
ylim([-220 220]); yticks(-220:40:220)
legend('MEMotorR', 'Location', 'best')
title ('Motor Torque vs Time')
exportgraphics(gcf, 'Plot #6 for Motor Torque.png','Resolution',300)
%How many seconds is the motor torque in the following conditions?
T = readtable('Autobahn Comfort.xlsx');
T.MEMotorR;
V = -220:40:220;
C = histcounts(T.MEMotorR,V) * 0.01;
Interval_Of_Torque_Nm = V(:);
Duration_Of_Torque_s = [C(:);NaN];
Motor_Torque = table(Interval_Of_Torque_Nm, Duration_Of_Torque_s, 'VariableNames',{'Interval of Motor Torque (Nm)','Duration of Motor Torque (s)'})
figure ; histogram(T.MEMotorR,V);
xlabel('Motor Torque (Nm)') % The histogram function automatically chooses an appropriate number of bins to cover the range of values in y
legend('Time (s)', 'Location', 'best')
title ('Duration of Motor Torque')
exportgraphics(gcf, 'Histogram #8 for Duration of Motor Torque.png','Resolution',300)
%
For ex. the graph on the right has some additional horizaontal blue line running in the middle (this is not supposed to be there) whilst the one on the left is perfectly fine. I am not sure how this has happened as I have not changed anything in the data of the Excel sheet. I have attached the Excel sheet, would you please be able to have a look at this?
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1454107/image.png)
This is the warning I receive in the workspace but not sure what it entirely means:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1454112/image.png)
See Also
Categories
Find more on Preprocessing Data 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!An Error Occurred
Unable to complete the action because of changes made to the page. Reload the page to see its updated state.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
Asia Pacific
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)