필터 지우기
필터 지우기

How can I quickly compare sizes of two Matrices?

조회 수: 75 (최근 30일)
Jakob Gillinger
Jakob Gillinger 2017년 5월 23일
답변: Matthew Heberger 2022년 12월 29일
I have two matrices of different sizes I'd like to compare before performing calculations with them - basically, I want to make sure their number of columns match. Now, as far as I can tell, I would have to use size() on both and compare their second value of the resulting vector, but since I can't index matrices that are temporary, I have to save the size vectors to a new variable, and then compare the indexed numbers. Is there a way to do it not only faster, but also without having to create a new variable?

채택된 답변

Stephen23
Stephen23 2017년 5월 23일
편집: Stephen23 2017년 5월 23일
Use size's optional second input to pick which dimension you want to check, e.g. to check if arrays A and B have the same number of columns:
size(A,2)==size(B,2)

추가 답변 (2개)

KSSV
KSSV 2017년 5월 23일
doc isequal..
  댓글 수: 1
Jakob Gillinger
Jakob Gillinger 2017년 5월 23일
That's not what I'm looking for. The only thing I need to check is whether the two matrices have the same number of columns, everything can and will be different.

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


Matthew Heberger
Matthew Heberger 2022년 12월 29일
Here is a good way to check that matrices A and B have the same size across all dimensions:
isequal(size(A), size(B))
This will return true if the matrices have the same size, and false if they have a different size. You can wrap it in an assert command if you want to raise an error and stop execution of the script when the two matrices are not the same size:
assert(isequal(size(A), size(B)))
Here is an example:
A = zeros(3, 1, 4);
B = zeros(3, 1, 4);
assert(isequal(size(A), size(B)))
% script will continue running after this...
This section will raise an error:
A = zeros(3, 1, 4);
B = zeros(3, 1);
assert(isequal(size(A), size(B)))
Error using assert
Assertion failed.

카테고리

Help CenterFile Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by