how to solve a cubic equation where the last term is an array

1 次查看(过去 30 天)
I have an equation with a set of constants in it and one array, I would like to solve the cubic equation for each of the V_total values which there are 365 of, and return the real roots for each V_total value into a single array of real solutions. I have tried using root() as well as fsolve() and in both cases it doesnt work. In the case of fsolve() i get the following message:
'fsolve' requires Optimization Toolbox.
Error in Hydroplant_Power_Calculation (line 28)
sol_x(i) = fsolve(@(V_total) fun(h, V_total(i)), rand());
Pasting my code below:
%declaring variables
Q_in = a column vector imported into matlab with 365 values
z = 70;
top_width = 223.6;
bottom_width = 61.6;
reservoir_length = 1;
%calculating reservoir volume
trapezium_area = ((top_width + bottom_width)/2)*z;
total_reservoir_volume = trapezium_area * reservoir_length *(1/2);
%now we need to find the volume added for each day
volume_added = Q_in.*86400; %in cubic meters
Q_out = 3; %metres cubed
volume_removed = Q_out * 86400;
V_total = volume_added - volume_removed; % volume at any given day
%EVERYTHING UP TO HERE IS FINE, NOW I TRY TO SOLVE THE CUBIC:
% Solving the cubic equation for h
%a = (1/19600)*top_width * reservoir_length;
%b = (1/280)*bottom_width*reservoir_length;
%c = 0;
%d = V_total;
%p = [a b c -d];
%h = roots(p)
%my second attempt:
fun = @(h, V_total) (1/19600)*top_width * reservoir_length*h.^3.+(1/280)*bottom_width*reservoir_length*h.^2-V_total
sol_x = zeros(size(V_total));
for i=1:numel(V_total)
sol_x(i) = fsolve(@(V_total) fun(h, V_total(i)), rand());
end

采纳的回答

Alan Weiss
Alan Weiss 2021-12-9
Try this instead of your code after %EVERYTHING UP TO HERE IS FINE:
sol_x = zeros(size(V_total));
for i = 1:numel(V_total)
fun = @(h)(1/19600)*top_width * reservoir_length*h^3.+(1/280)*bottom_width*reservoir_length*h^2-V_total(i);
sol_x(i) = fzero(fun,1);
end
Alan Weiss
MATLAB mathematical toolbox documentation
  2 个评论
Ryszard Nowacki
Ryszard Nowacki 2021-12-12
Hi,
Thanks, at the end the problem was i didint realise i need to download the optimisation toolbox for it, the code seems to work now. Thanks for your time anyway!
Alan Weiss
Alan Weiss 2021-12-12
If you use my answer you don't need Optimization Toolbox, only fzero, which is available in all MATLAB installations.
Alan Weiss
MATLAB mathematical toolbox documentation

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Solver Outputs and Iterative Display 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by