Below is my code and I get the corresponding error message. I'm trying to use fzero on the function defined below. What am I doing wrong?
1 view (last 30 days)
Show older comments
function [ y ] = mainFunc( v )
d = 0.15; % Diameter of sphere, meters
g = 9.8; % acceleration due to gravitym m/s^2
m = 0.5; % mass of sphere in kg
P = 101300; % N/m^2
R = 287; %gas cosntant
% Viscosisty constants b1 = 2.156954157e-14;
b2 = -5.332634033e-11;
b3 = 7.477905983e-8;
b4 = 2.527878788e-7;
T = linspace(213,333, 241); %temp in Kelvin
rho = 0*T;
u = 0*T;
for i = 1:length(T)
u(i) = b1*T(i)^3 + b2*T(i)^2 + b3*T(i) + b4;
end
for i = 1:length(T)
rho(i) = P / (R*T(i));
end
y = (24./(rho.*v*d./u) + 6./(1 + sqrt.(rho.*v*d./u)) + 0.4 - m*g) * (1/2) .* rho * v^2 * ((pi*d^2)/4) ;
end
ERROR MESSAGE >
HW5
Error using fzero (line 289)
FZERO cannot continue because user supplied function_handle ==> mainFunc failed with the error below.
Argument to dynamic structure reference must evaluate to a valid field name.
Error in HW5 (line 3) z = fzero(fun,x0)
0 Comments
Accepted Answer
John D'Errico
on 5 Nov 2014
Good start, but what you failed to show is how you called the blasted thing! Insufficient information.
Oh, and b1 is undefined, because you left it in a comment. My guess is that was done when you posted the function here though.
(You should learn to use the debugger!)
As it turns out though, the answer is simple. It seems like you think that a period should be placed in somewhat random places. For example, some of the multiplies are done using . but most of them with . but not all. I won't check that those always ended up as scalar operations, but I have a funny feeling they are not. That could be dangerous, although it was not the cause of your immediate problem.
y = (24./(rho.*v*d./u) + 6./(1 + sqrt.(rho.*v*d./u)) + 0.4 - m*g) * (1/2) .* rho * v^2 * ((pi*d^2)/4) ;
The problem? sqrt should NOT have a . after it.
More Answers (1)
Ali
on 5 Nov 2014
1 Comment
John D'Errico
on 7 Nov 2014
There is no need to add answers. Use the comments. You can post code in them too.
fzero expects functions to have scalar output, given scalar input. What do you expect it to do when your function returns an array of non-scalar shape?
>> size(y)
ans =
1 241
I have no idea what it is you ar trying to do, but I expect that you need to think about the problem, or explain clearly what it is you are trying to do.
See Also
Categories
Find more on Optimization in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!