# Using multiple error messages in one function file

조회 수: 7 (최근 30일)
Alyssa 2024년 2월 23일
답변: Fangjun Jiang 2024년 2월 23일
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

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

### 답변 (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');
This is an error message.

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

### 카테고리

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

R2023b

### Community Treasure Hunt

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

Start Hunting!

Translated by