- get rid of anti-pattern clear, close, clc
- get rid of all input commands
- use input arguments
- use the input validation to restrict the values to positive, etc:
Need help foolproofing my function code!
2 views (last 30 days)
Show older comments
MATLAB: Can someone help foolproof my function code? For example, a user can enter any unreasonable value such as negative weight or coordinates that don't make sense. Also Im sometimes getting a singularity warning message with the matrix. Thank you!
MATLAB FUNCTION:
function [FB, FC, FD] = CableForces()
% This function determines the force in two cables used to support
% an assigned crate.
clc
close all
clear all
help CableForces
disp('Note: Please enter the coordinates in the form of [x,y,z]!')
B = input('Enter the coordinates of B:');
C = input('Enter the coordinates of C:');
W = input('Enter the weight of the crate in lbs:');
% ultimate strength
UB=input('Ultimate strength of cable BD: ');
UC=input('Ultimate strength of cable CD: ');
dB=input('Cross-section diameter of cable BD: ');
dC=input('Cross-section diameter of cable CD: ');
AB=(pi/4)*dB^2;
AC=(pi/4)*dC^2;
Wrange = input('Enter the range of weights for which you wish to plot F vs W [W_min, W_max]:');
fb = B./norm(B);
fc = C./norm(C);
fd = [1 0 0];
A = [fb(1), fc(1), fd(1)
fb(2), fc(2), fd(2)
fb(3), fc(3), fd(3)];
b = [0, 0, W]';
sol = A\b;
FB = sol(1);
FC = sol(2);
FD = sol(3);
% stress finding
SB=FB/AB;
SC=FC/AC;
if SB>UB || SC>UC
fprintf('\nStress is high. So, cable will break\n')
else
fprintf('\nStress is low. So, cable will not break\n')
end
W = Wrange(1):Wrange(2);
FBg = zeros(size(W));
FCg = zeros(size(W));
FDg = zeros(size(W));
for i = 1:length(W)
b = [0, 0, W(i)]';
sol = A\b;
FBg(i) = sol(1);
FCg(i) = sol(2);
FDg(i) = sol(3);
end
plot(W,FBg,'r--p')
hold on
plot(W,FCg, 'b--p')
plot(W,FDg,'g--p')
grid on
title('FORCE vs WEIGHT')
xlabel('WEIGHT (lb)')
ylabel('FORCE (lb)')
legend('FB','FC','FD');
end
1 Comment
Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!