Adding characters to a matrix
显示 更早的评论
I'm having trouble with my error message to work.
I have an assignment to calculate the total variance, variance of the diagonal and the variance of the antidiagonal.
And if the input is anything but: 1 matrix with only numbers in it. There should be an error code and the function will be stopped.
My problem here is that when i have the input:
[varAlongDiag, varAlongAntiDiag, varTotal] = e2_2([1,2,3;4,5,6;g])
I get: "Undefined function or variable 'g'."
Do I need to make the matrix accept characters or undefined variables to get my error msg to be delivered instead?
Help much appreciated!
function [varAlongDiag, varAlongAntiDiag, varTotal] = e2_2(A, varargin)
if nargin == 1 && isnumeric(A) && ismatrix(A)
disp ('You only have 1 input')
disp ('Your input is a matrix')
disp ('Your input is only numbers')
B = diag(A); %Extracting the elements of the diagonal of "A"
D = flip(A); %Flipping the original matrix
E = diag(D); %Extracting the elements of the flipped matrix
varAlongDiag = var(B(:));
varAlongAntiDiag = var(E(:));
varTotal = var(A(:));
else
error('Your input can only include one matrix with numbers only!')
end
5 个评论
You can't mix letters into a numeric array. In your case you didn't put 'g' as a char either (which would not have been valid for that reason) so it expects g to be a variable. So your code should not be trying to handle inputs that are impossible to create in the first place.
cell arrays would be an example of a potentially mixed input that you would need to error on. Which your code is already doing with the isnumeric check anyway so it looks fine at a glance, though I haven't given rigorous thought to all the possible invalid inputs you can have.
e.g
{ [1,2,3];[4,5,6];'g' }
is a valid variable to create, but should be rejected by your function (i.e. throw an error, which it does)
Star Strider
2019-10-8
At some point before calling your function, you need to define ‘g’ as some value (or as a symbolic variable).
Marcus Niklasson
2019-10-8
Adam
2019-10-8
Yes, it seems to do that to me. Although it seems somewhat contrived to add the varargin argument since you simply want to check that in fact no other arguments are passed in anyway. Usually you would do this simply be declaring your function as:
function [varAlongDiag, varAlongAntiDiag, varTotal] = e2_2(A)
and Matlab would throw its own error if you try to pass any extra arguments into it.
Marcus Niklasson
2019-10-8
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!