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

조회 수: 2 (최근 30일)
Ryszard Nowacki
Ryszard Nowacki 2021년 12월 9일
댓글: Alan Weiss 2021년 12월 12일
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
Torsten
Torsten 2021년 12월 9일
It seems you don't have a valid licence for the Optimization Toolbox which is required to use "fsolve".

댓글을 달려면 로그인하십시오.

채택된 답변

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