가변 개수의 선을 표시하도록 최적화된 chart 클래스
이 예제에서는 가변 개수의 선을 표시하도록 chart 클래스를 최적화하는 방법을 보여줍니다. chart 클래스는 기존 line 객체를 재사용하기 때문에, 선 개수가 자주 바뀌지 않는 경우에 특히 차트 성능이 향상될 수 있습니다. 최적화되지 않은 좀 더 간단한 버전의 chart 클래스는 가변 개수의 선을 갖는 chart 클래스 항목을 참조하십시오.
이 차트는 YData
행렬에 포함된 열의 개수만큼 선을 표시하고, 국소 극값에 원형 마커를 표시합니다. 아래의 코드는 다음 작업을 수행하는 방법을 보여줍니다.
각각 선과 마커에 대한 객체를 저장하는
PlotLineArray
및ExtremaLine
이라는 2개의 속성을 정의합니다.ExtremaLine
객체를 초기화하는setup
메서드를 구현합니다.PlotLineArray
크기를 가져오는update
메서드를 구현한 다음,YData
의 열 개수에 따라 해당 배열에서 객체를 더하거나 뺍니다.
클래스를 정의하려면 다음 코드를 편집기에 복사하고 쓰기 가능한 폴더에 OptimLocalExtremaChart.m
이라는 이름으로 저장하십시오.
classdef OptimLocalExtremaChart < matlab.graphics.chartcontainer.ChartContainer % c = OptimLocalExtremaChart('XData',X,'YData',Y,Name,Value,...) % plots one line with markers at local extrema for every column of matrix Y. % You can also specify the additonal name-value arguments, 'MarkerColor' % and 'MarkerSize'. properties XData (:,1) double = NaN YData (:,:) double = NaN MarkerColor {validatecolor} = [1 0 0] MarkerSize (1,1) double = 5 end properties(Access = private,Transient,NonCopyable) PlotLineArray (:,1) matlab.graphics.chart.primitive.Line ExtremaLine (:,1) matlab.graphics.chart.primitive.Line end methods(Access = protected) function setup(obj) obj.ExtremaLine = matlab.graphics.chart.primitive.Line(... 'Parent', obj.getAxes(), 'Marker', 'o', ... 'MarkerEdgeColor', 'none', 'LineStyle',' none'); end function update(obj) % Get the axes ax = getAxes(obj); % Create extra lines as needed p = obj.PlotLineArray; nPlotLinesNeeded = size(obj.YData, 2); nPlotLinesHave = numel(p); for n = nPlotLinesHave+1:nPlotLinesNeeded p(n) = matlab.graphics.chart.primitive.Line('Parent', ax, ... 'SeriesIndex', n, 'LineWidth', 2); end % Update the lines for n = 1:nPlotLinesNeeded p(n).XData = obj.XData; p(n).YData = obj.YData(:,n); end % Delete unneeded lines delete(p((nPlotLinesNeeded+1):numel(p))) obj.PlotLineArray = p(1:nPlotLinesNeeded); % Replicate x-coordinate vectors to match size of YData newx = repmat(obj.XData(:),1,size(obj.YData,2)); % Find local minima and maxima and plot markers tfmin = islocalmin(obj.YData,1); tfmax = islocalmax(obj.YData,1); obj.ExtremaLine.XData = [newx(tfmin); newx(tfmax)]; obj.ExtremaLine.YData = [obj.YData(tfmin); obj.YData(tfmax)]; obj.ExtremaLine.MarkerFaceColor = obj.MarkerColor; obj.ExtremaLine.MarkerSize = obj.MarkerSize; % Make sure the extrema are on top uistack(obj.ExtremaLine, 'top'); end end end
클래스 파일을 저장하고 나면 차트의 인스턴스를 만들 수 있습니다. 예를 들면 다음과 같습니다.
x = linspace(0,2)'; y = cos(5*x)./(1+x.^2); c = OptimLocalExtremaChart('XData',x,'YData',y);
이제 매 반복 시 플롯에 선을 추가하는 for
루프를 만듭니다. chart 객체는 기존의 모든 선을 유지하고, i
마다 선을 하나씩 추가합니다.
for i=1:10 y = cos(5*x+i)./(1+x.^2); c.YData = [c.YData y]; end