Why isn't the hold on feature working? It only shows my last plot.

36 views (last 30 days)
figure();
plot(ans.p_controller, 'b')
hold on
plot(ans.pd_controller, 'r')
plot(ans.pi_controller, 'g')
plot(ans.pid_controller, 'k')
hold off
xlabel('Time (sec)')
ylabel('Rotation (Degrees)')
legend('P Controller', 'PD Controller', 'PI Controller', 'PID Controller')
title('Closed Loop Controllers')
grid on
  1 Comment
Walter Roberson
Walter Roberson on 28 Oct 2024 at 2:13
  1. Possibly the other data is all NaN or inf
  2. Possibly the other data is the same as the last data, so the last plot is exactly on top of the other plots.

Sign in to comment.

Answers (1)

Image Analyst
Image Analyst on 28 Oct 2024 at 2:15
How did you get "ans"? ans is a reserved keyword that gets changed very frequently, like when you call a function without accepting any return arguments. You should NEVER use it as the name of your variable. Calling plot without any return argument will return the handle to the plot in ans, thus overwriting whatever you had in ans. Each call to plot will overwrite ans.
Please call your "ans" variable by another name and then try it. It should work.
help plot
plot - 2-D line plot This MATLAB function creates a 2-D line plot of the data in Y versus the corresponding values in X. Vector and Matrix Data plot(X,Y) plot(X,Y,LineSpec) plot(X1,Y1,...,Xn,Yn) plot(X1,Y1,LineSpec1,...,Xn,Yn,LineSpecn) plot(Y) plot(Y,LineSpec) Table Data plot(tbl,xvar,yvar) plot(tbl,yvar) Additional Options plot(ax,___) plot(___,Name,Value) p = plot(___) Input Arguments X - x-coordinates scalar | vector | matrix Y - y-coordinates scalar | vector | matrix LineSpec - Line style, marker, and color string scalar | character vector tbl - Source table table | timetable xvar - Table variables containing x-coordinates string array | character vector | cell array | pattern | numeric scalar or vector | logical vector | vartype() yvar - Table variables containing y-coordinates string array | character vector | cell array | pattern | numeric scalar or vector | logical vector | vartype() ax - Target axes Axes object | PolarAxes object | GeographicAxes object Name-Value Arguments Color - Line color [0 0.4470 0.7410] (default) | RGB triplet | hexadecimal color code | "r" | "g" | "b" | ... LineStyle - Line style "-" (default) | "--" | ":" | "-." | "none" LineWidth - Line width 0.5 (default) | positive value Marker - Marker symbol "none" (default) | "o" | "+" | "*" | "." | ... MarkerIndices - Indices of data points at which to display markers 1:length(YData) (default) | vector of positive integers | scalar positive integer MarkerEdgeColor - Marker outline color "auto" (default) | RGB triplet | hexadecimal color code | "r" | "g" | "b" | ... MarkerFaceColor - Marker fill color "none" (default) | "auto" | RGB triplet | hexadecimal color code | "r" | "g" | "b" | ... MarkerSize - Marker size 6 (default) | positive value DatetimeTickFormat - Format for datetime tick labels character vector | string DurationTickFormat - Format for duration tick labels character vector | string Examples openExample('graphics/CreateLinePlotExample') openExample('graphics/PlotMultipleLinesExample') openExample('graphics/CreateLinePlotFromMatrixExample') openExample('graphics/SpecifyLineStyleExample') openExample('graphics/SpecifyLineStyleColorAndMarkerExample') openExample('graphics/DisplayMarkersAtSpecificDataPointsExample') openExample('graphics/SpecifyLineWidthMarkerSizeAndMarkerColorExample') openExample('graphics/AddTitleAndAxisLabelsExample') openExample('matlab/SpecifyDurationTickFormatsExample') openExample('graphics/PlotTableDataExample') openExample('graphics/PlotTableMutliVariablesExample') openExample('graphics/PlotSpecifyAxes19bExample') openExample('graphics2/ChangeLinePropertiesUsingHandlesExample') openExample('graphics/PlotCircleExample') See also title, xlabel, ylabel, xlim, ylim, legend, hold, gca, yyaxis, plot3, loglog, Line Properties Introduced in MATLAB before R2006a Documentation for plot doc plot Other uses of plot AggregateBayesianOptimization/plot alphaShape/plot antenna.Circle/plot backscatterBicyclist/plot backscatterPedestrian/plot Battery.Parameters/plot Battery.Pulse/plot Battery.PulseSequence/plot BayesianOptimization/plot blm/plot cfit/plot cgdatasetnode/plot cgrules/plot cgv.CGV/plot clusterDBSCAN/plot clustergram/plot clustering.evaluation.CalinskiHarabaszEvaluation/plot comm.MemorylessNonlinearity/plot comm.Ray/plot conjugateblm/plot cornerPoints/plot customblm/plot cylinderModel/plot DataMatrix/plot diffuseblm/plot digraph/plot driving.heremaps.LaneTopology/plot driving.Path/plot drivingScenario/plot dtree/plot empiricalblm/plot esbacktest/plot eyeMask/plot fairnessMetrics/plot frd/plot graph/plot HeatMap/plot iddata/plot idnlarx/plot idnlhw/plot imageviewset/plot InflationCollisionChecker/plot KAZEPoints/plot laneBoundarySegment/plot lassoblm/plot LayerGraph/plot LeastSquaresResults/plot lidarScan/plot lime/plot LinearModel/plot localavfit/plot localmod/plot localmulti/plot matlab.buildtool.Plan/plot mixconjugateblm/plot mixsemiconjugateblm/plot monovslam/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 pulseWaveformLibrary/plot reidentificationmetrics/plot RepeatedMeasuresModel/plot rfchain/plot rgbdvslam/plot roadrunnerHDMap/plot rocmetrics/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.sdi/plot Simulink.SimulationData.Parameter/plot slrealtime.ProfilerData/plot stereovslam/plot sweepset/plot tall/plot timeseries/plot tireData/plot tireModel/plot trajectoryErrorMetrics/plot umargin/plot varbacktest/plot vehicleCostmap/plot wdectree/plot xregmodel/plot xregtransient/plot xregtwostage/plot
  3 Comments
Image Analyst
Image Analyst on 28 Oct 2024 at 2:43
OK, that seems unexpected and inconsistent with most/all of the other functions that return their value in ans if you don't explicitly accept it into a named variable. Well anyway, it's not good to have variables of your own named ans.
埃博拉酱
埃博拉酱 on 28 Oct 2024 at 13:35
@Image Analyst Some functions check for nargout. If it is 0, it does not produce a return value to improve performance.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!