I can't figure out how to correctly do a function handle
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I didn't know how to make the function script work the way I wanted it to
function F = Tension(b, c, w)
global Lb Lc W
Lb = b;
Lc = c;
W = w;
F = @t;
end
function T = t(D)
global Lb Lc W
T = Lb*Lc*W./(D.*sqrt(Lc.^2-D.^2));
end
This did not work when i tried it in this script file:
% The following functions compute the tension force in the cable T:
% Lb = beam length in meters
% Lc = cable length in meters
% W = weight in Newtons
% D = distance of the cable attachment point to the beam pivot in meters
%
% Example Values:
% Lb = 5
% Lc = 3
% W = 400
% Function:
F = Tension(b, c, w);
% Prompts for and accept values for Lb, Lc, W:
b = input('Enter the length of beam, Lb, in meters:')
c = input('Enter the length of cable, Lc, in meters:')
w = input('Enter the weight of suspended object, W, in Newtons:')
% Compute and display value of D that minimizes T, tension.
D = fminbnd(F,0,7);
disp('The value of D that minimizes tension, T:')
disp(D)
% Compute and display minimum tension, T, value.
T = t(D);
disp('The minimum tension, T, value:')
disp(T)
% Determine how much the value of D can vary from it’s optimal value
% before the tension increases by more than 10% from it’s minimum.
Dvar = fzero(@t, [3, 500]);
disp('How much D can vary before T increases by more than 10%:')
disp(Dvar)
The values of b, c, w is input by the user. The error is at line 37 T= t(D)
0 Kommentare
Antworten (1)
Guillaume
am 8 Okt. 2015
You basically have a function that takes four inputs (Lb, Lc, W, and D) and you want to pass it to a function that wants a function with only one arguments (D), the other three being constant. It looks like you tried to achieve that with global variables. While that would work, it's not recommended and can be achieved without it:
function F = tension(b, c, w)
%returns a function handle that calculates tension against distance with the given constants
%b: beam length
%c: cable length
%w: object weight
%F: a function handle that returns tension for a given distance
F = @(d) t(b, c, w, d); %an anonymous function that only takes one argument
end
function T = t(b, c, w, d)
T = b*c*W./(d.*sqrt(c.^2-d.^2));
end
In you main code, you need to obtain the function handle F after you've acquired the constants b, c, and w, and it is the function you should pass to fzero:
%...
w = input('Enter the weight of suspended object, W, in Newtons:')
F = tension(b, c, w); %F is a function handle with fixed constant b, c, w as input by the user.
%...
Dvar = fzero(F, [3 500]);
1 Kommentar
Siehe auch
Kategorien
Mehr zu Scope Variables and Generate Names finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!