# Using multiple error messages in one function file

6 visualizzazioni (ultimi 30 giorni)
Alyssa il 23 Feb 2024
Risposto: Fangjun Jiang il 23 Feb 2024
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
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Risposte (1)

Fangjun Jiang il 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.
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Categorie

Scopri di più su Functions in Help Center e File Exchange

R2023b

### Community Treasure Hunt

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

Start Hunting!

Translated by