Info

此问题已关闭。 请重新打开它进行编辑或回答。

Fixing an eroor in simple if-function

1 次查看(过去 30 天)
David
David 2020-4-8
关闭: MATLAB Answer Bot 2021-8-20
Hi everyone,
I got a problem with an if-else function. I want to put the correct 4x2 matrix so here is my function:
function matrix(n)
if size(n)== 4 2
fprintf(' Congrats \n')
else
fprintf(' Incorrect!!Please input a 4x2 matrix \n')
end
The problem I am facing is that whatever matrix I input they all show that INCORRECT!! PLEASE INPUT A 4X2 MATRIX, even when i input 4x2 matrix, i encounter same problem. Can anyone help me? I think the problem is at size(n)== 4 2
Thanks you

回答(1 个)

Geoff Hayes
Geoff Hayes 2020-4-8
David - yes the problem is with your condtion. Note that size will return an array where each element is the size of the dimension. Trying to compare this to 4 2 will result in an Unexpected MATLAB expression error (at least it does for me) so you need to think of an alternative way to do this check. From size, you can get the number of rows and the number of columns by supplying the appropriate dimension input.
numberOfRows = size(n,1);
numberOfColumns = size(n,2);
Now that you know the size of each dimension, you can then do the appropriate comparison
if size(n,1) == 4 && size(n,2) == 2
% congrats...
end
One further check that you may want to add is to ensure that the number of dimensions is two (since a 4x2x3 matrix will pass the above condition). See ndims for details.

此问题已关闭。

Community Treasure Hunt

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

Start Hunting!

Translated by