필터 지우기
필터 지우기

Need help foolproofing my function code!

조회 수: 2 (최근 30일)
Alan Barraza
Alan Barraza 2020년 12월 2일
편집: Stephen23 2020년 12월 2일
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
Stephen23
Stephen23 2020년 12월 2일
편집: Stephen23 2020년 12월 2일
  1. get rid of anti-pattern clear, close, clc
  2. get rid of all input commands
  3. use input arguments
  4. use the input validation to restrict the values to positive, etc:

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

답변 (0개)

카테고리

Help CenterFile Exchange에서 Mathematics에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by