MATLAB Answers

How to get fzero to work on an array?

15 views (last 30 days)
Daniel Beeson
Daniel Beeson on 24 May 2020
Answered: Alan Weiss on 26 May 2020
I'm trying to solve fzero for each value of x in an array, and I get theis error:
Operands to the || and && operators must be convertible to logical scalar values.
Error in fzero (line 444)
while fb ~= 0 && a ~= b
Error in hw5_code (line 14)
mach = fzero(eqn,[.16 2]);
x = .2:.1:.6;
r = .3 + 3.*((x-.5).^2);
g = 1.4;
p0 = 7576;
t0 = 1033;
pb = 100;
a = pi.*r.^2;
a_star = pi.*(.3^2);
eqn = @(m) (a./a_star).^2 - (1./m.^2 .*((2./(g+1)) .* (1 + (((g-1)./2) .* m.^2))).^((g+1)./(g-1)));
mach = fzero(eqn,[.16 2]);
t = t0 .* ((1+ (((g-1)/2) .* mach.^2)).^-1);
p = p0 .* (1+ (((g-1)/2) .* mach.^2)).^-(g/(g-1));
rho = p./(287.*t);
air = sqrt(g.*287.*t);
v = mach.*air;
m_dot = rho .* v .* a;
a1 = 1 + ((2.*g)./(1+g)).*((mach.^2) -1);
a2 = (2 + (g-1).*(mach.^2))./((g+1).*(mach.^2));
change_entropy = log(a1.*a2) - (((g-1)/g).*log(a1));

  3 Comments

Ameer Hamza
Ameer Hamza on 24 May 2020
Why are you passing a 1x2 vector as an initial guess to fzero()?
Star Strider
Star Strider on 24 May 2020
A (1x2) vector is entirely appropriate, providing a sign change exists on the interval.
Stephen Cobeldick
Stephen Cobeldick on 24 May 2020
"Why are you passing a 1x2 vector as an initial guess to fzero()?"
The fzero documentation states that x0 may be scalar or a 2-element vector, in which case "fzero checks that fun(x0(1)) and fun(x0(2)) have opposite signs, and errors if they do not. It then iteratively shrinks the interval where fun changes sign to reach a solution." This is clearly very useful when the bracketing range is known.

Sign in to comment.

Answers (1)

Alan Weiss
Alan Weiss on 26 May 2020
I don't know if this is what you wanted, but I got it to work by making a loop for fzero:
x = .2:.1:.6;
r = .3 + 3.*((x-.5).^2);
g = 1.4;
p0 = 7576;
t0 = 1033;
pb = 100;
a = pi.*r.^2;
a_star = pi.*(.3^2);
eqn = @(m) (a./a_star).^2 - (1./m.^2 .*((2./(g+1)) .* (1 + (((g-1)./2) .* m.^2))).^((g+1)./(g-1)));
%%
% mach = fzero(eqn,[.16 2]);
mach = zeros(size(eqn(.16)));
for i = 1:length(mach)
tp = zeros(size(mach));
tp(i) = 1;
mach(i) = fzero(@(x)dot(tp,eqn(x)),[0.15 1]);
end
%%
t = t0 .* ((1+ (((g-1)/2) .* mach.^2)).^-1);
p = p0 .* (1+ (((g-1)/2) .* mach.^2)).^-(g/(g-1));
rho = p./(287.*t);
air = sqrt(g.*287.*t);
v = mach.*air;
m_dot = rho .* v .* a;
a1 = 1 + ((2.*g)./(1+g)).*((mach.^2) -1);
a2 = (2 + (g-1).*(mach.^2))./((g+1).*(mach.^2));
change_entropy = log(a1.*a2) - (((g-1)/g).*log(a1));
Alan Weiss
MATLAB mathematical toolbox documentation

  0 Comments

Sign in to comment.

Tags


Translated by