Issue with fzero command when finding when the 2 curves are first equal.

The 2 pressure curves are:
t = linspace(0, 6, 121);
y1 = 3 * cos(2*t);
y2 = 2 * sin(t)
in the script here is my current code:
function F = h(z);
t = linspace(0, 6, 121);
F(1) = 3/cos(2*t)-2*sin(t);
end
My interval when calling the fzero command will be [0 6].
I know the code is extremely redundant but im getting the error of the indices on the left side are not compatibile with the size of the right side within the function. I was wondering is someone can help me resolve this issue.

 采纳的回答

Your data are not described by functions (including anonymous functions), so fzero is likely not appropriate. You can find the first instance when the two are equal using the interp1 interpolation function:
t = linspace(0, 6, 121);
y1 = 3 * cos(2*t);
y2 = 2 * sin(t);
zci = @(v) find(v(:).*circshift(v(:), [-1 0]) <= 0); % Returns Approximate Zero-Crossing Indices Of Argument Vector
yd = y1 - y2; % Subtract
ydidx = zci(yd); % Get First Index
t_v = interp1(yd(ydidx(1)+[-1 1]), t(ydidx(1)+[-1 1]), 0); % Closer Approximation: ‘t’
y1_v = interp1(t, y1, t_v); % Closer Approximation: ‘y1’
figure
plot(t, y1, t, y2)
hold on
plot(t_v, y1_v, '+r', 'MarkerSize',15)
hold off
grid
The red ‘+’ marks the first point of equality. You can do the same for the others if you want to (step through the ‘ydidx’ indices in a for loop to find them, using my code for the first one).
EDIT — (11 Mar 2019 at 16:04)
If you want to use your assignments as functions, and then use them with fzero, try this:
t = linspace(0, 6, 121);
y1 = @(t) 3 * cos(2*t);
y2 = @(t) 2 * sin(t);
t0 = 1;
t_intercept = fzero(@(t) y1(t)-y2(t), t0)
producing:
t_intercept =
0.594164318632733
To use both of them with fzero, create an additional anonymous function (either within the fzero call as I did here, or as a separate function) and evaluate the two functions within it.

更多回答(0 个)

类别

Community Treasure Hunt

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

Start Hunting!

Translated by