Plot with dates goes wrong - octave

I run into this problem: when I plot in Octave without x values, it's ok. when I add x values (which are supposed to be dates, but I don't impose the date format), it goes weird
ab = rand(96,1);
close all
figure
plot(ab)
Gives this figure:
close all
figure
plot(datenum('01-Nov-2020 00:00','dd-mmm-yyyy HH:MM'):1/24/4:datenum('01-Nov-2020 23:45','dd-mmm-yyyy HH:MM'),ab)
Gives this figure:
As you can see, the x values are all within 1 day, so I don't even know why the x tick show more than 1 day...
Anyone would have a smart explanation?

EDIT: As Tasos stated in an earlier answer, it's a "problem of OpenGL being unable to deal with the precision involved when adding small numbers to a large number".
From my point of view, that's "just" an Octave bug, MATLAB (tested with MATLAB Online) doesn't show that behaviour. It seems, Octave has problems with small x intervals when the actual x value is relatively high, cf.
subplot(2, 1, 1);
x = linspace(800000, 800000 + 2*pi, 100);
y = sin(x);
plot(x, y);
subplot(2, 1, 2);
x = linspace(0, 2*pi, 100);
y = sin(x);
plot(x, y);
The corresponding output is:
It seems, some x values are getting "merged"!? I haven't searched in depth for reported bugs on that issue...
But, to work around that issue in your case, you could try plotting the data starting at 0, and later just adapt the xticklabels:
% Data
ab = rand(96, 1);
figure(1);
% Plot without dates
subplot(3, 1, 1);
plot(ab);
xlim([1, 96]);
% Plot with dates (standard, faulty)
subplot(3, 1, 2);
dates = linspace(datenum('01-Nov-2020 00:00', 'dd-mmm-yyyy HH:MM'),
datenum('01-Nov-2020 23:45', 'dd-mmm-yyyy HH:MM'),
size(ab, 1))
plot(dates, ab);
datetick('x', 'dd-mm-yyyy HH:MM');
xlim([dates(1), dates(end)]);
% Plot with dates (custom, correct)
subplot(3, 1, 3);
# For plotting, subtract start date
dates_for_plot = dates - datenum('01-Nov-2020 00:00', 'dd-mmm-yyyy HH:MM')
plot(dates_for_plot, ab);
datetick('x', 'dd-mm-yyyy HH:MM');
# Add custom xticklabels with re-added start date
xlim([dates_for_plot(1), dates_for_plot(end)]);
xticklabels(cellstr(datestr(xticks + datenum('01-Nov-2020 00:00',
'dd-mmm-yyyy HH:MM'))));
That'd be the output:

Related

How to plot a 2d Function in MATLAB

I am trying to plot a simple equation in MATLAB.
The equation is
z = x^2 - y^2, for -3 <= x <= 3, -3 <= y <= 3.
The current code that I have is
x = -3:3;
y = -3:3;
z = (x.^2) - (y.^2);
plot(z)
The result is
Please help me in this case because I am not sure if the code and graph is correct. Thank you very much.
This is not a piecewise function. A Piecewise Function is a function defined by multiple sub-functions, where each sub-function applies to a different interval in the domain. There is only one function here that takes two arrays of the same length. The calculations yield a vector of zeros, due to the input arrays. If you change either one of the vectors, that is "x" or "y", you will see a nonzero plot. Your code works as expected.
There is a lot going wrong here: Let's start at the beginning:
x = -3:3;
y = -3:3;
If we evaluate these they both will return an vector of integers:
x =
-3 -2 -1 0 1 2 3
This means that the grid on which the function is evaluated is going to be very coarse. To alleviate this you can define a step size, e.g. x = 3:0.1:3 or use linspace, in which case you set the number of samples, so e.g. x = linspace(-3, 3, 500). Now consider the next line:
z = (x.^2) - (y.^2);
If we evaluate this we get
z =
0 0 0 0 0 0 0
and you plot this vector with the 2d-plotting function
plot(z)
which perfectly explains why you get a straight line. This is because the automatic broadcasting of the arithmetic operators like minuse (-) just subtracts values entry-wise. You however want to evaluate z for each possible pair of values of x and y. To do this and to get a nice plot later you should use meshgrid, and use a plotting function like mesh to plot it. So I'd recommend using
[X,Y] = meshgrid(x,y);
to create the grid and then evaluate the function on the grid as follows
Z = X.^2 - Y.^2;
and finally plot your function with
mesh(X,Y,Z);

How to fix DIM error in jaccard distance?

I am trying to create a Jaccard distance from the Y. I do not know even if is correct what I am coding. I took an error message about DIM...i have checked on the internet but I cannot figure out. Maybe my code in total is wrong
Y=[1,0; 1,1; 1,0]
m = 1 - [(sum(min((Y-Y(1, :)), (Y-Y(2, :)), (Y-Y(3, :))), 3))/(sum(max(Y-Y(1, :)), (Y-Y(2, :)), (Y-Y(3, :)), 3))]
I expect a 3x3 matrix but i receive an error
error: min: DIM must be a valid dimension
It's not clear to me how what you're trying to do here (a Jaccard distance requires two inputs, not clear what your inputs are), but in any case you have syntactical errors here.
To begin with, you've got imbalanced brackets in your 'max' function (presumably it should be max((Y-Y(1,:)), ... rather than max(Y-Y(1,:)) (notice the single opening bracket) which ends the function call. The fact that you're using a lot of superfluous brackets and bad indentation / spacing style makes it even harder to spot these. E.g. a better way to write this (purely visually) might be:
m = 1 - [ sum( min( Y - Y(1,:), ...
Y - Y(2,:), ...
Y - Y(3,:) ), 3 ) ...
/ ...
sum( max( Y - Y(1,:), ...
Y - Y(2,:), ...
Y - Y(3,:) ), 3 ) ...
];
Or, better yet, capture the intermediate results into meaningfully named intermediate variables, so that your code reads like english and is easier to follow and debug, i.e.
VectorOfMinima = min( Y - Y(1,:), Y - Y(2,:), Y - Y(3,:) );
VectorOfMaxima = max( Y - Y(1,:), Y - Y(2,:), Y - Y(3,:) );
SumOfMinima = sum( VectorOfMinima, 3);
SumOfMaxima = sum( VectorOfMaxima, 3);
Jaccard = 1 - ( SumOfMinima / SumOfMaxima );
Having said all that, your use of min and max is wrong though. I'm not quite sure what you want to achieve, but effectively min (and max respectively) can only be used in the form min(X, [], DIM) which determines along which dimension to obtain minima in for the matrix X, or min(X, Y) which returns a new matrix with the minimum of either X or Y at each position. You're effectively calling min as min(X, Y, Z) which is not a valid call for min.

What is the best way to calculate the duration from incode/outcode in MySQL?

I have written the following to calculate the duration from incode/outcode but was wondering if there was a better way of calculating this.
As TIMEDIFF() is a time specific function, I was only able to use it to calculate the difference between the fist 9 characters. I then subtract the last two characters and add them back to the 'Duration'.
HH:MM:SS:FF (FF for frames) and the framerate is 25fps.
incode = '10:00:01:00'
outcode = '10:01:05:02'
select CONCAT(SUBSTR(TIMEDIFF(outcode, incode), 1, 8), ':',
LPAD((SUBSTR(outcode, 10, 11) - SUBSTR(incode, 10, 11)), 2, 0)) as 'Duration';
Duration should be:
00:01:04:02
MySQL Version: 5.5+
If you're using 5.5.x or later then you can consider the following...
SET #timecode_2 = '10:01:05:02';
SELECT SEC_TO_TIME(TIME_TO_SEC(SUBSTRING_INDEX(#timecode_2,':',3))+SUBSTRING_INDEX(#timecode_2,':',-1)*0.04) x;
Outputs:
x
10:01:05.0800000

administer drug dose at certain time step in octave

I am doing a simple task on ocatve.
I have to administer drug dose at day 1,7,21 and 28..
i wrote a function like that:
function xdot = f (x,t)
a=[1;7;21;28]
drug=0; ### initially drug is zero
if (t==a)
drug=drug+57.947;
else
drug=drug+0;
endif
xdot=(-0.4077)*(x)+ drug; passing the value of drug to differential equation
endfunction
In the main file i called this function in lsode:
t=linspace(0,30,30);
x0=0;
y=lsode(#ex,x0,t); ### ex is the file name where function is written
plot(t,y,'o')
This program doesn't work.. it displays all the time zero value for drug. Can anybody help me that how to administer dug dose with certain time step by manipulating linspace function.
It looks like you have a simple clearance model, and at each time in a, you want the dose to be delivered instantaneously. That is, at each time in a, the amount of drug in the subject increases by 57.947.
If that is the model that you have in mind, implementing it in the formula for xdot will not work well. You would actually need to implement it as a "delta function", and lsode won't work with that.
Instead, I recommend solving the problem in stages, corresponding to the time intervals [0, 1], [1, 7], [7, 21], and [21, 28]. During one stage, the differental equation is simply xdot = -0.4077*x. In the first stage, the initial condition is 0. In the next stage, the initial condition is the final value of the previous stage plus the dosage amount 57.947.
Here's a script:
dose = 57.947;
a = [1 7 21 28 30];
x0 = 0.0;
t0 = 0;
t = [];
y = [];
for t1 = a
tinterval = linspace(t0, t1, 2*(t1 - t0) + 1);
yinterval = lsode(#(x, t) -0.4077*x, x0, tinterval);
t = [t tinterval];
y = [y yinterval'];
t0 = t1;
x0 = yinterval(end) + dose;
end
plot(t, y, "linewidth", 2);
The script creates this plot:
Note that the differential equation xdot = -k*x has the solution x0*exp(-k*(t-t0)), so the call to lsode could be replaced with
yinterval = x0*exp(-0.4077*(tinterval - t0));
If you do this, also remove the transpose from yinterval two lines below:
y = [y yinterval];
If you want to keep the implementation of the administration of the drug dose within the formula for xdot, you'll need to distribute it over a small time interval. It could be implemented as a short rectangular pulse of width w and height 57.974/w. You'll also need to ensure that lsode takes sufficiently small internal time steps (less than w) so that it "sees" the drug dose.
You probably want replace t==a by ismember (t, a). Also, you should erase the else clause as it has no effect on the answer.
UPDATE
Consider rewriting your function as:
function xdot = f (x,t)
xdot = -0.4077*x + 57.947*ismember (t, [1 7 21 28])
endfunction

Correct solution for this tensor

I'm implementing the system in this paper and I've come a little unstuck correctly implementing the radial tensor field.
All tensors in this system are of the form given on page 3, section 4
R [ cos(2t), sin(2t); sin(2t), -cos(2t) ]
The radial tensor field is defined as:
R [ yy - xx, -2xy; -2xy, -(yy-xx) ]
In my system I'm only storing R and Theta, since I can calculate the tensor based off just that information. This means I need to calculate R and Theta for the radial tensor. Unfortunately, my attempts at this have failed. Although it looks correct, my solution fails in the top left and bottom right quadrants.
Addendum: Following on from discussion in the comments about the image of the system not working, I'll put some hard numbers here too.
The entire tensor field is 800x480, the center point is at { 400, 240 }, and we're using the standard graphics coordinate system with a negative y axis (ie. origin in the top left).
At { 400, 240 }, the tensor is R = 0, T = 0
At { 200, 120 }, the tensor is R = 2.95936E+9, T = 2.111216
At { 600, 120 }, the tensor is R = 2.95936E+9, T = 1.03037679
I can easily sample any more points which you think may help.
The code I'm using to calculate values is:
float x = i - center.X;
float xSqr = x * x;
float y = j - center.Y;
float ySqr = y * y;
float r = (float)Math.Pow(xSqr + ySqr, 2);
float theta = (float)Math.Atan2((-2 * x * y), (ySqr - xSqr)) / 2;
if (theta < 0)
theta += MathHelper.Pi;
Evidently you are comparing formulas (1) and (2) of the paper. Note the scalar multiple l = || (u_x,u_y) || in formula (1), and identify that with R early in the section. This factor is implicit in formula (2), so to make them match we have to factor R out.
Formula (2) works with an offset from the "center" (x0,y0) of the radial map:
x = xp - x0
y = yp - y0
to form the given 2x2 matrix:
y^2 - x^2 -2xy
-2xy -(y^2 - x^2)
We need to factor out a scalar R from this matrix to get a traceless orthogonal 2x2 matrix as in formula (1):
cos(2t) sin(2t)
sin(2t) -cos(2t)
Since cos^2(2t) + sin^2(2t) = 1 the factor R can be identified as:
R = (y^2 - x^2)^2 + (-2xy)^2 = (x^2 + y^2)^2
leaving a traceless orthogonal 2x2 matrix:
C S
S -C
from which the angle 'tan(2t) = S/C` can be extracted by an inverse trig function.
Well, almost. As belisarius warns, we need to check that angle t is in the correct quadrant. The authors of the paper write at the beginning of Sec. 4 that their "t" (which refers to the tensor) depends on R >= 0 and theta (your t) lying in [0,2pi) according to the formula R [ cos(2t), sin(2t); sin(2t) -cos(2t) ].
Since sine and cosine have period 2pi, t (theta) is only uniquely determined up to an interval of length pi. I suspect the authors meant to write either that 2t lies in [0,2pi) or more simply that t lies in [0,pi). belisarius suggestion to use "the atan2 equivalent" will avoid any division by zero. We may (if the function returns a negative value) need to add pi so that t >= 0. This amounts to adding 2pi to 2t, so it doesn't affect the signs of the entries in the traceless orthogonal matrix (since 'R >= 0` the pattern of signs should agree in formulas (1) and (2) ).