Using multiple error messages in one function file
5 次查看(过去 30 天)
显示 更早的评论
I am trying to make a function that solves for a vector but needs to meet certain conditions. If it does not meet certain conditions the function should display an error message and leave the function. I was able to write one of my error messages to work, but on my .mlx file, it won't run another set of variables I'm feeding the function and display a solution. I've been using disp() and return functions to rememdy this. Any guidance would be appreciated.
Matrices I'm trying to solve
Kii = [2 -2 0 0 0; -2 3 -1 0 0; 0 -1 3 -2 0; 0 0 -2 -3 -1; 0 0 0 0 0];
fii = [5 0 0 0 -1]';
solvability(Kii,fii);
Kiii = [2 -2 0 0 0; -2 3 -1 0 0; 0 -1 3 -2 0; 0 0 -2 -3 -1; 0 0 0 0 0];
fiii = [0 0 0 0 0]';
solvability(Kiii,fiii);
Function file created:
function [d] = solvability(K, f)
check = det(K); % determine the determinant of K for singularity
if check ~= 0 % if K is non-singular
disp('The system has a unique solution')
d=K\f;
disp('displacements = ')
disp(d)
return
else
if norm(f)==0 % check if right hand side = 0
error('ERROR: The right hand side is a zero vector and there exist non-zero solutions')
end
if norm(f)~=0
error('ERROR: The right hand side is a non-zero vector and there can be no solution or infinite solutions')
end
end
end
0 个评论
回答(1 个)
Fangjun Jiang
2024-2-23
When the program encounters an error, it will stop the execution.
Don't use error(). Instead, use fprintf() to get the message out. The fid=2 gives you the red font, error-like message. Well, not in MATLAB Answers, not in live script output, but certainly in MATLAB Command Window.
Or, use warning()
fprintf(2, 'This is an error message.\n');
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Symbolic Math Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!