Using multiple error messages in one function file

5 views (last 30 days)
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);
Error using solution>solvability
ERROR: The right hand side is a non-zero vector and there can be no solution or infinite solutions
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

Answers (1)

Fangjun Jiang
Fangjun Jiang on 23 Feb 2024
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');
This is an error message.

Categories

Find more on Symbolic Math Toolbox in Help Center and File Exchange

Products


Release

R2023b

Community Treasure Hunt

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

Start Hunting!