How can I plot only certain values from an array?

조회 수: 66 (최근 30일)
Ahsan Khan
Ahsan Khan 2014년 12월 17일
답변: Ankit Jain 2017년 4월 21일
hi there, say I have an array [1,3,5,7,1,5,1,7,8,1]. I want to plot ONLY say value 1 from this array in accordance with the index in which the value resides in. so for the above array I want to plot for only value 1 occurrence: the value 1 shows up on index (0,4,6,and 9) so the plot will have an x-axis 1-10 and will only show a spike in the y direction when there is a value of 1 in the array. I have attached a an image as to what the result should look like. please help. thank you in advance. SN

채택된 답변

Adam
Adam 2014년 12월 17일
편집: Adam 2014년 12월 17일
a = [1,3,5,7,1,5,1,7,8,1];
idx = find( a == 1 );
figure; hAxes = gca;
stem( hAxes, idx, ones(numel(idx)) );
xlim( hAxes, [1 10] );
If you want to see the spikes more clearly you can also add e.g.
ylim( hAxes, [0 2] );
  댓글 수: 1
Thorsten
Thorsten 2014년 12월 17일
편집: Thorsten 2014년 12월 17일
Or as a one-liner :-)
stem(find(a==1), ones(numel(find(a==1))), 'k', 'Marker','None', 'LineWidth', 3), box off, axis([0 12 0 2])
and if you want just dots, use plot instead of stem:
plot(find(a==1), ones(numel(find(a==1))), 'ko', 'MarkerSize', 6, 'MarkerFaceColor', 'k')

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Sudharsana Iyengar
Sudharsana Iyengar 2014년 12월 17일
just another method. This is round about way and will actually take more time to execute.
j=1;
for i=1:length(a)
if a(i)==1
b(j,1)=i;
b(j,2)=1;
j=j+1;
end
end
plot (b(:,1),b(;,2))
This will store the values of i for which the value is equal to 1. Which you can plot.

Ankit Jain
Ankit Jain 2017년 4월 21일
Above all method are only applicable if the value to be plotted is same, what about if one wants varied values to be plotted?

카테고리

Help CenterFile Exchange에서 Line Plots에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by