Home > Back-end >  How can I plot in horizontal lines along X axis corresponding to a value on the y axis? [MATLAB]
How can I plot in horizontal lines along X axis corresponding to a value on the y axis? [MATLAB]

Time:01-29

I have 2 arrays Q and Z. I want to plot Q on the y-axis and Z on the x-axis. The elements of Z are 0s and 1s.

What I want is to draw a horizontal line from one '1' to the next '1'. E.g. in vector Z, the first 1 to the next 1, has its corresponding y value as the first element of Q, Then the 3rd 1 to the fourth 1 has its y value as the 2nd value in Q and so on.

now i will have several _ _ _ (horizontal lines spanning length of the distance between the 1s as plots)

any help will be appreciated.

CodePudding user response:

You can find the endpoints of each horizontal line with find(), then plot the lines with plot.

Q = [1 2 3 4];
Z = [1 0 1 1 0 0 1 1 1 0 1 0 1];
z_endpoints = find(Z);

figure;
for i = 1:numel(Q)
    plot(z_endpoints([i*2-1,i*2]),Q([i,i]))
    hold on
end
hold off

CodePudding user response:

Assuming that Q and Z are column vectors, you could do something like this:

Q2=[Q,Q];
inds=1:numel(Z);
inds=inds(Z==1);
X=reshape(inds',2,numel(inds)/2);

At this point, Q2 and X should have the same dimensions (two-column matrices). Then plot the horizontal lines beside each other:

plot(X,Q2)

Or above each other, starting at x=0 with different lengths:

X2=[zeros(numel(Q),1),diff(X)]
plot(X2,Q2)

I'm not at a computer so I can't confirm details on returned dimensions.

Hope it helps!

  • Related