Info
This question is closed. Reopen it to edit or answer.
Fixing an eroor in simple if-function
1 view (last 30 days)
Show older comments
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
0 Comments
Answers (1)
Geoff Hayes
on 8 Apr 2020
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.
0 Comments
This question is closed.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!