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

1 view (last 30 days)
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
  1 Comment
Torsten
Torsten on 9 Dec 2021
It seems you don't have a valid licence for the Optimization Toolbox which is required to use "fsolve".

Sign in to comment.

Accepted Answer

Alan Weiss
Alan Weiss on 9 Dec 2021
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 Comments
Ryszard Nowacki
Ryszard Nowacki on 12 Dec 2021
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 on 12 Dec 2021
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

Sign in to comment.

More Answers (0)

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!