Reputation: 3693
I have a matrix where some values have -1
as an indication that there was an error. Normally I would just use ylim([0 100])
to not show these values in my graph, but when using line graph the connection will still drop down to the point. I want a chart that consists of lines, not a scatter plot. Is there a simple way of ignoring negative values when plotting a line and only connect positive values when using the plot function in MATLAB?
I have written a small example program which behaves similarly, but the way I use seems a little "too complicated" and I want to know if there is an easier way to achieve this. It works fine as I put the values to NaN
, and now the x
and y
values are the same amount. However deleting or sorting out the values from the vector will lead to different amount of x
and y
values.
I was hoping for a modification or a flag or something.
x = 2*rand(10) - rand(10)
xx = 10:10:100;
figure;
for i=1:length(x)
for j=1:length(x(i,:))
if x(i,j) < 0
x(i,j) = NaN;
end
end
end
plot(xx,x)
Please note that this is only an example, the whole code would be too large to post here.
When having non-corresponding x
-values (so that the plot function simply uses 1,2,3...
and so on for the corresponding y
values) this can be achieved by using
plot(x(x>0))
In this case, the corresponding values are different, in the real code they are measured data, here I simply use a 10th step for simplification.
x = 2*rand(10) - rand(10)
xx = 10:10:100;
plot(xx,x(x>0))
The above code will error with the message "Vectors must be the same length".
Upvotes: 1
Views: 4127
Reputation: 24179
This is just like using NaN
instead of negative values, only that the original vector is not modified at all. You might notice that this solution is vectorized.
y = 2*randn(10,1) - randn(10,1);
figure(); plot(1:numel(y), y./(y<=0) );
Upvotes: 4
Reputation: 14863
a = [50, -1, 10, 5, 8, 22, -1];
b = a > 0;
c = a(b);
Output:
c
[50, 10, 5, 8, 22]
Now you can plot c
[~, s] = size(c);
xx = 1:1:s;
You could also do it directly without saving the calculation and modifying it. just plot it.
plot(x(x>0))
Upvotes: 1