Guys why doesn't this code display 'Hello'?
2 次查看(过去 30 天)
显示 更早的评论
A = zeros(4,2);
while unique(A,'rows') ~= A
disp('Hello')
end
0 个评论
回答(2 个)
Steven Lord
2018-8-25
The ~= operator can handle inputs that are the same size as well as inputs of different size where one is a scalar (scalar expansion) and has been able to handle them for a very long time. In recent releases, it can also handle inputs that are different sizes where the inputs are compatible sizes (implicit expansion.)
In your situation A is 4-by-2 and unique(A, 'rows') is 1-by-2. These are compatibly sized, and (A ~= unique(A, 'rows')) will be a 4-by-2 logical array. If unique(A, 'rows') had had 4 rows that call to ~= would have worked as well because it can handle inputs that are the same size. But if unique(A, 'rows') had had 2 or 3 rows the ~= operator would have thrown an error. [4 2] and [2 2] are not compatible sizes and neither are [4 2] and [3 2].
Because of how you've constructed A, each row of A is the same as the row vector returned by unique(A, 'rows'). Therefore A ~= unique(A, 'rows') has all false entries. When you pass a non-scalar array as the condition for a while statement, the body of the while statement executes ONLY if the condition is nonempty and all the elements in the condition are nonzero. For your code, the condition is nonempty but not all the elements are nonzero.
If you want to check that A has only unique rows, call unique with the 'stable' flag and compare them using isequal.
A = [1 2 3; 7 8 9; 4 5 6];
allRowsUnique = isequal(A, unique(A, 'rows', 'stable'))
0 个评论
Mohamed Habiballa Abdelmoez
2018-8-25
Because the condition of the while loop to work is false since "unique(A,'rows')" is EQUALE TO "A" itself.
Try to use this:
A = zeros(4,2);
while unique(A,'rows') == A %%I changed the condition to be '=='
disp('Hello')
end
2 个评论
Stephen23
2018-8-25
编辑:Stephen23
2018-8-25
"But isn't unique(A,'rows') = [0 0] and A =[0 0; 0 0; 0 0; 0 0]? They aren't equal right?"
== does not work how the way that you are thinking: == tests for element-wise equivalency, and its input arguments may be of different sizes. This is explained in its help: "Numeric or string inputs A and B must either be the same size or have sizes that are compatible (for example, A is an M-by-N matrix and B is a scalar or 1-by-N row vector). For more information, see Compatible Array Sizes for Basic Operations." When you follow the link you it explains how implicit scalar expansion will apply to the inputs that you are using.
If you want to test if variables are the same size and contain the same values in the same positions then you need to use isequal.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!